??运算符 |
?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。
可以为 null 的类型可以包含值,或者可以是未定义的。?? 运算符定义当可以为 null 的类型分配给非可以为 null 的类型时返回的默认值。 如果在尝试将可以为 null 值的类型分配给不可以为 null 值的类型时没有使用 ?? 运算符,则会生成编译时错误。 如果使用强制转换,且当前还未定义可以为 null 值的类型,则会引发 InvalidOperationException 异常。
有关更多信息,请参见 可以为 null 的类型(C# 编程指南)。
即使 ??运算符的两个参数都是常量,也不能将其结果视为常量。
{
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");
}
}
可以为 null 的类型是 System .
Nullable <
T >
结构的实例。
num = Null
Nullable object must have a value.
-
可以为 null 的类型表示可被赋值为 null 值的值类型变量。 无法创建基于引用类型的可以为 null 的类型。 (引用类型已支持 null 值。) -
语法 T? 是 Nullable < T > 的简写,此处的 T 为值类型。 这两种形式可以互换。 -
为可以为 null 的类型赋值的方法与为一般值类型赋值的方法相同,如 int? x = 10;或 double? d = 4.108. 对于可以为 null 的类型,也可向其赋 null 值: int? x = null. -
如果基础类型的值为 null,请使用 Nullable < T > . GetValueOrDefault 方法返回该基础类型所赋的值或默认值,例如 int j = x.GetValueOrDefault(); -
请使用 HasValue 和 Value 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value; -
如果此变量包含值,则 HasValue 属性返回 True;或者,如果此变量的值为空,则返回 False。 -
如果已赋值,则 Value 属性返回该值。 否则,将引发 System . InvalidOperationException 。 -
HasValue 的默认值为 false。 Value 属性没有默认值。 -
对可以为 null 的类型,还可以使用 == 和 != 运算符,例如 if (x != null) y = x;
-
-
使用 ?? 运算符分配默认值,在将当前值为 null 的可以为 null 的类型赋值给不可以为 null 的类型时,将应用该默认值,如 int?。 x = null; int y = x ??-1; -
不允许使用嵌套的可以为 null 的类型。 将不编译下面一行: Nullable<Nullable<int>> n;
来源:msdn帮助文档