C# 中的 ?? 运算符

?? 称作【null合并运算符】

使用对象:

用于定义可以为 null 值的类型和引用类型的默认值。

值判断:

如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。(记住这句唯一的人话)

官方示例:

class NullCoalesce
{
    static int? GetNullableInt()
    {
        return null;
    }

    static string GetStringValue()
    {
        return null;
    }

    static void Main()
    {
        // ?? operator example.
        int? x = null;

        // y = x, unless x is null, in which case y = -1.
        int y = x ?? -1;

        // Assign i to return value of method, unless
        // return value is null, in which case assign
        // default value of int to i.
        int i = GetNullableInt() ?? default(int);

        string s = GetStringValue();
        // ?? also works with reference types. 
        // Display contents of s, unless s is null, 
        // in which case display "Unspecified".
        Console.WriteLine(s ?? "Unspecified");
    }
}

说明:用人话翻译就是.....

示例1:y = -1

  1.  int y=x ?? -1; 表示给 y 赋值, x 或者 -1;
  2.  int? x = null; 说明 x 为可空类型,且值为空;
  3. ?? 运算符左侧若为空,返回右侧,所以返回 -1;
  4. 所以 y 拿到 -1;

示例2:i = 0

  1. int i = GetNullableInt() 表示将 GetNullableInt()赋值给 i ;
  2. i 为不可空类型,所以需要看 GetNullableInt() 类型;
  3.  GetNullableInt() 为可空的 int 且返回空 ,所以赋值时需要使用 ?? ;
  4. 目的是在 GetNullableInt() 返回null 时,使 i 可以拿到默认值;
  5. int 的默认值为 0;
  6. 不用?? 的话会报错;

示例3:打印 Unspecified

  1. ?? 可用于引用类型的示例;
  2. 打印 s 的值或者 Unspecified;
  3.  string 类型的默认值就是null ,且GetStringValue() 返回null,所以 s 就是null ;
  4. 当 ?? 左侧为null 时,返回右侧的值;
  5. 所以打印 Unspecified ;

异常:

使用该运算符可能会抛两个异常,直接看微软原话:

 The ?? operator defines the default value to be returned when a nullable type is assigned to a non-nullable type. If you try to assign a nullable value type to a non-nullable value type without using the ?? operator, you will generate a compile-time error. If you use a cast, and the nullable value type is currently undefined, an InvalidOperationException exception will be thrown.

 ?? 运算符定义当可以为 null 的类型分配给非可以为 null 的类型时返回的默认值。 如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。 如果使用强制转换,且当前还未定义可以为 null 值的类型,则会引发 InvalidOperationException 异常。

讲人话就是:

如果你要把【可空】复赋值给【不可空】,用了??,就给你返回 default

没用?? 就给你报 compile-time,如果还妄想用强转,直接给你 InvalidOperationException

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

那个那个鱼

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

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

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

打赏作者

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

抵扣说明:

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

余额充值