?? 运算符

?? 运算符称为 null 合并运算符,用于定义可以为 null 值的类型和引用类型的默认值。如果此运算符的左操作数不为 null,则此运算符将返回左操作数;否则返回右操作数。

备注
 
 

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

有关更多信息,请参见 可以为 null 的类型(C# 编程指南)

即使 ??运算符的两个参数都是常量,也不能将其结果视为常量。

示例
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");
    }
}
-----------------------------------------------------------

可以为 null 的类型

可以为 null 的类型是 System . Nullable < T > 结构的实例。 可以为 null 的类型可以表示其基础值类型正常范围内的值,再加上一个 null 值。 例如, Nullable<Int32> 读作“可以为 null 的 Int32”,可以将其赋值为 -2147483648 到 2147483647 之间的任意值,也可以将其赋值为 null 值。 可以赋给 Nullable<bool> 的值包括 truefalsenull。 在处理数据库和其他包含不可赋值的元素的数据类型时,将 null 赋值给数值类型或布尔型的功能特别有用。 例如,数据库中的布尔型字段可以存储值 truefalse,或者,该字段也可以未定义。

num = Null

Nullable object must have a value.

可以为 null 的类型概述
 
 

可以为 null 的类型具有以下特性:

  • 可以为 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();

  • 请使用 HasValueValue 只读属性测试是否为空和检索值,例如 if(x.HasValue) j = x.Value;

    • 如果此变量包含值,则 HasValue 属性返回 True;或者,如果此变量的值为空,则返回 False。

    • 如果已赋值,则 Value 属性返回该值。 否则,将引发 System . InvalidOperationException

    • HasValue 的默认值为 falseValue 属性没有默认值。

    • 对可以为 null 的类型,还可以使用 == 和 != 运算符,例如 if (x != null) y = x;

  • 使用 ?? 运算符分配默认值,在将当前值为 null 的可以为 null 的类型赋值给不可以为 null 的类型时,将应用该默认值,如 int?。x = null; int y = x ??-1;

  • 不允许使用嵌套的可以为 null 的类型。将不编译下面一行: Nullable<Nullable<int>> n;

posted @ 2012-08-27 16:06  路灯下的诗人  阅读(453)  评论(0编辑  收藏  举报