一、概述 * X0 H7 R! J+ p. m4 r; z \" N6 z 当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举.. A2 ?8 G6 Q6 ~3 o. [6 o 二、是否为 null - @! Q0 q% x ^% m7 L 如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:6 z* T! t2 q, {1 Y1 V
方式一:== null. J/ X9 i, }0 n+ P6 g+ 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; }
}
E E3 Z) p- F2 k- F) x1 S. O方式二:is null ; _: d( y1 Z/ I
if (stuList.Count == 0)
{
Console.WriteLine("stuList is empty");
}
# l* y, X8 n1 b: u$ R3 `# E
方式二:!stuList.Any() // 确定序列是否包含任何元素。 ; {' g p6 X$ \! `6 e/ W+ I// 返回结果:2 B3 i9 X/ X& n! c. d
// true 如果源序列中不包含任何元素,则否则为 false。6 x; y G. H" L
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; }
}