C#中??運(yùn)算符的作用


如果 ?? 運(yùn)算符的左操作數(shù)非空,
該運(yùn)算符將返回左操作數(shù),否則返回右操作數(shù)。

注意:

可空類型可以包含值,或者可以是未定義的。
?? 運(yùn)算符定義當(dāng)可空類型分配給非可空類型時返回的默認(rèn)值。
如果在將可空類型分配給非可空類型時不使用 ?? 運(yùn)算符,將生成編譯時錯誤。
如果使用強(qiáng)制轉(zhuǎn)換,并且當(dāng)前未定義可空類型,
將發(fā)生 InvalidOperationException 異常。


//微軟官方實(shí)例應(yīng)用說明
using System;
class MainClass
{
    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");
    }
}


原文鏈接:C#中??運(yùn)算符的作用