如果此运算符的左操作数不为 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");
    }
}


相关文章:

  • 2022-12-23
  • 2021-10-19
  • 2021-11-11
  • 2021-08-31
  • 2021-12-16
  • 2021-06-18
  • 2021-06-09
  • 2021-07-21
猜你喜欢
  • 2021-07-06
  • 2022-01-04
  • 2022-12-23
  • 2021-11-10
  • 2021-04-23
相关资源
相似解决方案