?? 運算符(C# 參考)


 

?? 運算符稱為 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"); } } 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM