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; }
}
if (stuList.Count == 0)
{
Console.WriteLine("stuList is empty");
}
) Q7 N! t& W$ ~3 t
方式二:!stuList.Any() // 确定序列是否包含任何元素。9 D& O. Y, M) P1 z1 M9 G y
// 返回结果:) C6 d+ Z+ ], Z
// true 如果源序列中不包含任何元素,则否则为 false。0 a* K+ R6 v' E, V( M3 ]/ X
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 p* _2 _- }; [7 Y$ C. k' q
这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。* B+ k+ R/ ^* f1 h6 ]" x