?? 称作【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
- int y=x ?? -1; 表示给 y 赋值, x 或者 -1;
- int? x = null; 说明 x 为可空类型,且值为空;
- ?? 运算符左侧若为空,返回右侧,所以返回 -1;
- 所以 y 拿到 -1;
示例2:i = 0
- int i = GetNullableInt() 表示将 GetNullableInt()赋值给 i ;
- i 为不可空类型,所以需要看 GetNullableInt() 类型;
- GetNullableInt() 为可空的 int 且返回空 ,所以赋值时需要使用 ?? ;
- 目的是在 GetNullableInt() 返回null 时,使 i 可以拿到默认值;
- int 的默认值为 0;
- 不用?? 的话会报错;
示例3:打印 Unspecified
- ?? 可用于引用类型的示例;
- 打印 s 的值或者 Unspecified;
- string 类型的默认值就是null ,且GetStringValue() 返回null,所以 s 就是null ;
- 当 ?? 左侧为null 时,返回右侧的值;
- 所以打印 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