一、概述* i; @" D- w4 v" i% F b
当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举. * e: b. r3 j2 H( U, [6 M, z; i二、是否为 null % X: o8 f9 U* q# z 如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式: 8 T9 S. L" s! L- A方式一:== null# q, Q+ Z0 R: B; f- N
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; }
}
- q8 U& v# v; x8 {方式二:is null S N5 F* {. b M& h' K
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; }
}
0 _; R* o$ ?) e) z4 r% F 这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。 & W- i6 W6 p, N5 l/ J: b. Y