Loading

可为NULL的值类型

1.检查是否可空

1.1 判断该值指示 Nullable 对象是否具有基础类型的有效值

int? b = 10;
if (b.HasValue) { Console.WriteLine($"b is {b.Value}"); }

//若 b = null
else { Console.WriteLine("b does not have a value"); }

Console.ReadLine();
// Output:
// b is 10

1.2 将可为空的值类型的变量与 null 进行比较

int? c = 7;
if (c != null)
{
    Console.WriteLine($"c is {c.Value}");
}
else
{
    Console.WriteLine("c does not have a value");
}
// Output:
// c is 7

2.可空类型转换 ??

2.1 使用 Null合并操作符 进行类型转换

int? a = 28;
int b = a ?? -1;
Console.WriteLine($"b is {b}");  // output: b is 28

int? c = null;
int d = c ?? -1;
Console.WriteLine($"d is {d}");  // output: d is -1

解释
??(空合并运算符): a??b 当a为null时则返回b,a不为null时则返回a本身

2.2 使用基础值类型强转

int? n = null; 
//int m1 = n;   // Doesn't compile 
int n2 = (int)n;    // Compiles, but throws an exception if n is null

在运行时,如果可为空的值类型的值为 null,则显式强制转换将抛出 InvalidOperationException

3.空合并运算符

3.1 以前写法

        static void Main(string[] args)
        {
            int? a = null;
            if (a == null)
            {
                a = 4;
            }

            Console.WriteLine(a);
            Console.Read();
        }
        // Output: a = 4

3.2 使用 ??

        static void Main(string[] args)
        {
            int? a = null;
            a ??= 5;

            Console.WriteLine(a);
            Console.Read();
        }
        // Output: a = 5

4.微软官方文档

可为空的值类型
可分配有null的值类型 (Nullable)
?? 和 ??= 运算符

posted @ 2022-08-24 16:48  DotNeter-Hpf  阅读(29)  评论(0编辑  收藏  举报