在C# 中的可为空值类型表示除了可以接收原有值类型外还可以接收NULL值
例如:int? a =1; int? b=null;
在使用可为空值类型时可以配合 条件运算符 ?? (没错,就是两个问号!)配合使用。
例如:int? a =1; int b= a ?? 1;
这种方式需要指定为NULL时的默认值。
放一段代码用于演示的更直观;
//值类型和可为空值类型正常赋值,需要指定为空时的默认值
int? a = 111;
int b = a ?? 1;
Console.WriteLine($"a 等于 {a},b 等于 {b}");
int? c = null;
int d = c ?? 1;
Console.WriteLine($"c 等于 {c},d 等于 {d}");
//不指定默认值时,可以使用GetValueOrDefault()获取该值类型默认值
int? e = null;
int f = e.GetValueOrDefault();
Console.WriteLine($"e 等于 {e},f 等于 {f}");
执行结果如下图:
在使用逻辑运算符进行运算时也需要注意和基础值类型不一样的地方,如以下代码;
//在逻辑运算符中需要注意如下场景
int? g = 222;
int? h = null;
int? j = null;
Console.WriteLine($"g > h 等于{g > h}");
Console.WriteLine($"g < h 等于{g < h}");
Console.WriteLine($"g == h 等于{g == h}");
Console.WriteLine($"g >= h 等于{g >= h}");
Console.WriteLine($"g <= h 等于{g <= h}");
Console.WriteLine($"j > h 等于{j > h}");
Console.WriteLine($"j < h 等于{j < h}");
Console.WriteLine($"j == h 等于{j == h}");
Console.WriteLine($"j >= h 等于{j >= h}");
Console.WriteLine($"j <= h 等于{j <= h}");
执行结果如下图;
可为空值类型应用场景:
1.在进行非空判断时,只需要一段通用代码即可,而无需再单独为值类型数据进行单独处理。
可为空值类型 使用注意事项:
1.不要调用 GetType() 方法获取类型实例,该操作会导致 装箱操作。获取类型实例请使用 typeof()关键字进行。
2.不要使用 is 运算符 判断 int 或 int? ,is 运算符无法区分。请使用 Nullable.GetUnderlyingType(typeof())方法判断是否是 可为空值类型。