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; }
}
( F8 h8 k2 L9 l8 B/ K) @方式二:is null3 w$ e3 i7 b% O' N( f: a
三、是否为空# C& Q2 @6 u$ p' J2 B) i
在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现:$ `( S; A6 l2 V# l' o
方式一:stuList.Count == 0& i) E3 x k7 T. D3 n/ @) O0 [
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; }
}