C# 检查集合是否为空?

概述

当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举。

是否为 null

如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:

方式一:== null.

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; }    }

C# 检查集合是否为空?

方式二:is null

 if (stuList is null)

是否为空

在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现:

方式一:stuList.Count == 0

if (stuList.Count == 0)            {                Console.WriteLine("stuList is empty");            }

C# 检查集合是否为空?

方式二:!stuList.Any()   //     确定序列是否包含任何元素。

        //返回结果:

        // true 如果源序列中不包含任何元素,则否则为 false。

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

那如果我既想检查他是否为null又想检查是否为null,有没有简洁点的语法呢?

这时候我们就可以用 ?. 来操作了.

实例如下:

 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; }    }

C# 检查集合是否为空?

这样就可以保证stuList为null的时候获取集合的数量也不会引发异常.以上就是本节的全部内容,希望对你有用。