?? 运算符(C# 参考)

 

?? 运算符称为 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");
    }
}


posted @ 2014-10-20 17:31  dodo-yufan  阅读(5216)  评论(0编辑  收藏  举报