QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

查看: 2775|回复: 0

[C#/.NET] 检查集合是否为空

[复制链接]

等级头衔

积分成就    金币 : 2861
   泡泡 : 1516
   精华 : 6
   在线时间 : 1328 小时
   最后登录 : 2026-5-15

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老活跃会员

联系方式
发表于 2022-10-15 11:49:57 | 显示全部楼层 |阅读模式
一、概述
4 O" U, T8 Q8 @       当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举.
2 u- [- I4 m- _# R7 D' h二、是否为 null
2 u  @; ^( x" B0 T6 D       如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:
5 l- E# _  g2 q; q4 T  N: Z/ j- t方式一:== null
5 @- i* R) |  U: d+ q; `' m
class Program
    {
        static List<Student> stuList;
        static void Main(string[] args)
        {
            if (stuList == null)
            {
                Console.WriteLine("stuList is null");
            }
            Console.ReadKey();
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
1.jpg
& R9 w! i4 O) g% V方式二:is null
/ ?  h1 S7 |" u
if (stuList is null)
三、是否为空
! D& x2 {2 f: T5 w. `1 ]       在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现:3 u3 D1 c5 Z8 Z: _
方式一:stuList.Count == 0" r  e1 ], H6 E) N% }% i7 @
if (stuList.Count == 0)
            {
                Console.WriteLine("stuList is empty");
            }
2.jpg
1 L4 {( o! ]# k# y8 |+ O方式二:!stuList.Any()   //     确定序列是否包含任何元素。1 U" F9 |( o9 i1 P8 A
// 返回结果:4 _% g9 Q- \7 z, k0 m; P4 v
// true 如果源序列中不包含任何元素,则否则为 false。
/ e  _. ^: t" s; o
if (!stuList.Any())
            {
                Console.WriteLine("stuList is empty");
            }
      那如果我既想检查他是否为null又想检查是否为null,有没有简洁点的语法呢?这时候我们就可以用 ?. 来操作了。
; Y7 s& z% Y1 Z4 B# {实例如下:
class Program
    {
        static List<Student> stuList = new List<Student>();
        static void Main(string[] args)
        {
            //if (stuList is null)
            //{
            //    Console.WriteLine("stuList is null");
            //    throw new Exception("stuList is null");
            //}

            //if (!stuList.Any())
            //{
            //    Console.WriteLine("stuList is empty");
            //}

            stuList.Add(new Student() { Name = "zls",Age = 25});
            if (stuList?.Count != 0)
            {
                Console.WriteLine("StuList is neither null nor empty");
            }

            Console.ReadKey();
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }
3.jpg
$ M+ L. }0 X  ]! |: }! Q0 f       这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。
2 O6 E! z* n8 q5 M" \) C
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号|渝公网安备50010502503914号 )

GMT+8, 2026-6-23 16:09

Powered by paopaomj X3.5 © 2016-2025 sitemap

快速回复 返回顶部 返回列表