一、概述3 ]- a; C' N A2 A9 p
当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举." A8 C, \0 k3 k0 v% o 二、是否为 null5 L8 ]0 Y; t7 k8 Y
如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:+ s6 W. h. o$ {) ]4 k
方式一:== null + j; v* {8 P. J6 }
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; }
}
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; }
}
! B& r" {" c$ g" j9 {2 b/ H
这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。 3 p% r$ Y" I( U6 e