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; }
}
; W5 `9 W: _& O: M |方式二:is null5 a) Z3 K' r/ S8 ]" b0 R" f% n% {
if (stuList.Count == 0)
{
Console.WriteLine("stuList is empty");
}
) P: ?' U ]- u
方式二:!stuList.Any() // 确定序列是否包含任何元素。$ }* l5 k5 ?: z B: n. v9 b3 o
// 返回结果:( c: `: e5 j; i' l `8 Z
// true 如果源序列中不包含任何元素,则否则为 false。 % s- G4 F1 g. s( i0 m+ ^/ |
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; }
}
[; W2 b( Z8 ~: M/ q) ? 这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。 9 C+ M \/ h9 s0 B1 V3 F