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; }
}
+ u. y4 t X+ Y% b" w
方式二:is null ! M& ^9 ^# w# Z( R( e6 t
三、是否为空 2 M; w. g2 v d3 k2 [0 a 在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现:/ y5 k3 W f1 s' o" G. \9 X; Q
方式一:stuList.Count == 01 y1 v. h* }6 X: g ]- i. g
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; }
}
7 m5 V1 K3 u! u. x# ~ 这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。 / A& r1 ~5 q6 v+ j3 |' e2 b