一、概述
4 w9 {' y' \8 O. @' V 当一个集合作为入参传入另外一个方法时,我们首先需要判空处理,以免在空集合上处理引发异常,判空处理的方式有多种,下面就来一一列举.
) r: v; w( M3 o- Y* [% E5 H9 a0 ]9 h二、是否为 null7 X% i: o" @; G+ c" g9 B Z
如果一个集合没有实例化,那集合就是null,判null的常用以下几种方式:+ Z3 Q& ^3 E* h' l. f, W
方式一:== null; i& d% M$ b. W" K% ?& B) D
- 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; }
- }
3 q1 J7 N4 r- J; \+ h+ w. `! o方式二:is null
# R7 h; h; N# \ i9 E$ ^
三、是否为空2 U3 i5 C! h* I5 B
在上面我们先判断了集合不为null以后,如果还需要检查集合是否有元素,也是有多种方式可以实现: 1 }. F. @; {. k6 m
方式一:stuList.Count == 0 & G/ w! n/ X: i
- if (stuList.Count == 0)
- {
- Console.WriteLine("stuList is empty");
- }
/ @# [; j1 V6 X; [5 S: ~' V- H; y/ R S方式二:!stuList.Any() // 确定序列是否包含任何元素。 / ^/ \" a) H- j# {2 K
// 返回结果:
6 N0 I- Z# j/ K) D* j// true 如果源序列中不包含任何元素,则否则为 false。 0 q; T% M2 Y8 o$ u
- if (!stuList.Any())
- {
- Console.WriteLine("stuList is empty");
- }
那如果我既想检查他是否为null又想检查是否为null,有没有简洁点的语法呢?这时候我们就可以用 ?. 来操作了。
. H. ^3 p% j7 V+ C实例如下: - 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; }
- }
/ B1 K5 |4 o1 h ^ 这样就可以保证stuList为null的时候获取集合的数量也不会引发异常。
, C* q; D' V l( G |