?? 運算子(C# 參考)

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   io   os   ar   使用   

  • Visual Studio 2008
  • Visual Studio 2005
  • Visual Studio 2013
  • Visual Studio 2012
 

?? 運算子稱為 null 合并運算子,用於定義可以為 null 值的類型和參考型別的預設值。如果此運算子的左運算元不為 null,則此運算子將返回左運算元;否則返回右運算元。

備忘

可為 Null 的型別可以包含值,或者可以是未定義的。?? 運算子定義當可為 Null 的型別分配給非可為 Null 的型別時返回的預設值。如果在嘗試將可以為 null 值的類型分配給不可以為 null 值的類型時沒有使用 ?? 運算子,則會產生編譯時間錯誤。如果使用強制轉換,且當前還未定義可以為 null 值的類型,則會引發 InvalidOperationException 異常。

有關更多資訊,請參見可為 Null 的型別(C# 編程指南)。

即使 ?? 運算子的兩個參數都是常量,也不能將其結果視為常量。

樣本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"); }}

?? 運算子(C# 參考)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.