面向云技术架构 - 痴者工良

  • 首页
  • 资源导航
    • 值得收藏的网站导航
    • 本站文章导航
    • 资源下载
  • 教程文档
    • kubernetes 教程
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. .NET
  3. 正文

C# 可空集合类型

2022年8月6日 92点热度 1人点赞 0条评论
内容纲要

当集合为 null 时,代码如下:

            List<int>? _a = null;
            List<int>? _b = null;

            var a = _a?.Any() == false;
            var b = _a?.Any() == true;
            var c = _b?.Any() == false;
            var d = _b?.Any() == true;

当集合为 null 时,?.Any() == false 、?.Any() == true ,结果都是 false。

file

当集合为 不为 null ,元素数量为 0 时,代码如下:

            List<int>? _a = new List<int>();
            List<int>? _b = new List<int>();

            var a = _a?.Any() == false;
            var b = _a?.Any() == true;
            var c = _b?.Any() == false;
            var d = _b?.Any() == true;

file

结论是,能够正确表达意图。

如果想判断两个集合都不为 null,并且都有元素时:

            List<int>? _a = null;
            List<int>? _b = new List<int>();

            var result = _a?.Any() == true && _b?.Any() == true;

file

其中一个有不为 null 且有元素:

            List<int>? _a = null;
            List<int>? _b = new List<int>()
            {
                1,2
            };

            var result = _a?.Any() == true || _b?.Any() == true;

file

判断两者都是 null 或 没有元素,这个就麻烦,难写,例如下面代码就有 bug:

            List<int>? _a = null;
            List<int>? _b = new List<int>();

            var result = !(_a?.Any() == true && _b?.Any() == true);
            _b = new List<int>() { 1,2,3,4};
            result = !(_a?.Any() == true && _b?.Any() == true);

最好还是写扩展,不要试图在一行代码解决所有:

        internal static bool IsNullOrEmpty<T>(this IEnumerable<T>? source)
        {
            if (source == null) return true;
            if (source.Count() == 0) return true;
            return false;
        }

语法糖虽然好用,但是需要注意规范,不然会写出黑暗代码。

file

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: c 空集合 类型
最后更新:2022年8月6日

痴者工良

高级程序员劝退师

点赞
< 上一篇

文章评论

取消回复

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号