可为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)
?? 和 ??= 运算符

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DotNeter-Hpf

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值