可空值类型

可空值类型是System.Nullable这个struct的实例
可空值类型除了可以正确的表示其底层数据类型的范围,还可以表示null

举例Nullable

bool
True
False
Nullable
True
False
Null

  1. static void Main(string[] args)
  2. {
  3. string str = "asdfghjkl";
  4. // 想要定位字母m在字符串中的哪个位置,如果没有的话返回null,int无法接收
  5. Nullable<int> indexOfM = str.IndexOf('m');
  6. //但是上面那样写比较麻烦,.NET提供了一个语法糖,用int?就可以表示可空类型
  7. int? indexOfM2 = str.IndexOf('m');
  8. }

Null和空,空白string

  1. string name="Nick";
  2. string name = null;
  3. string name = "";
  4. string name = " ";
  5. 判断Null和空,空白string
  6. if(name==null){..} // 直接判断是否为null
  7. if(string.isNullOrEmpty(name)){..} // 判断是否是null还是""的string
  8. if(string.isNullOrWhiteSpace(name)){..}
  9. // 判断是否包含空格的空string
  10. static void Main()
  11. {
  12. string str = "";
  13. System.Console.WriteLine(string.IsNullOrEmpty(str)); // True
  14. System.Console.WriteLine(string.IsNullOrWhiteSpace(str)); // True
  15. string str2 = null;
  16. System.Console.WriteLine(string.IsNullOrEmpty(str2)); // True
  17. System.Console.WriteLine(string.IsNullOrWhiteSpace(str2)); // True
  18. string str3 = " ";
  19. System.Console.WriteLine(string.IsNullOrEmpty(str3)); // False
  20. System.Console.WriteLine(string.IsNullOrWhiteSpace(str3)); // True
  21. }

Nullable的常用属性和方法

  1. .HasValue //null:false; 否则:true
  2. int? intValue = null;
  3. System.Console.WriteLine(intValue.HasValue); // print:false
  4. .Value // 底层值类型的值
  5. static void Main()
  6. {
  7. int? intValue = 3;
  8. System.Console.WriteLine(intValue.Value); // print:3
  9. int? intValue2 = null;
  10. // print: InvalidOperationException
  11. System.Console.WriteLine(intValue2.Value);
  12. }
  13. .GetValueOrDefault() // 底层值类型的值或该类型的默认值
  14. int? intValue = null;
  15. System.Console.WriteLine(intValue.GetValueOrDefault()); // print:0
  16. .GetValueOrDefault(默认值) // 底层值类型的值或指定的默认值
  17. static void Main()
  18. {
  19. int? intValue = null;
  20. System.Console.WriteLine(intValue.GetValueOrDefault(5)); // print:5
  21. }


Nullable比较

  1. static void Main()
  2. {
  3. int? a = 1;
  4. int? b = 1;
  5. System.Console.WriteLine(a == b); //True
  6. int? c = 1;
  7. int? d = null;
  8. System.Console.WriteLine(c == d); //False
  9. int? e = null;
  10. int? f = null;
  11. System.Console.WriteLine(e == f); //True
  12. }

Nullable转换

T → Nullable<T>隐式转换
Nullable<T> → T显示转换

  1. static void Main()
  2. {
  3. {
  4. int i = 3;
  5. int? j = i;
  6. }
  7. {
  8. int? i = 3;
  9. //无法将类型“int?”隐式转换为“int”。存在一个显式转换(是否缺少强制转换?)
  10. int j = i;
  11. //只能显示转换
  12. int j = (int)i;
  13. }
  14. }

检查Null的操作符

?: 条件操作符
?? Null合并操作符
?. Null条件操作符
?[ 针对索引表示法的操作预算