2010-08-07 95 views

回答

24

這被稱爲空合併運算符和它充當以下,假定a是一個可爲空int和b是一個正常的INT

b = a ?? 1; 

等於

b = (a != null ? (int)a : 1); 

等於

if(a != null) 
    b = (int)a; 
else 
    b = 1; 

因此

public NameValueCollection Metadata 
{ 
    get { return metadata ?? (metadata = new NameValueCollection()); } 
} 

擴大看起來應該像這樣

public NameValueCollection Metadata 
{ 
    get 
    { 
     if(metadata == null) 
      return (metadata = new NameValueCollection()); 
     else 
      return metadata; 
    } 
} 

這是某種一個襯墊Singleton模式,因爲吸氣回報元數據(一個初始化的NameValueCollection對象)每次請求時,期望第一次它在那個時候是空的,所以它初始化它並且然後返回它。這是主題,但請注意,這種單身模式的方法不是線程安全的。

0

這是coalesce操作符,它檢查null。

statement ?? fallback如果語句評估爲null,則使用fallback。請參閱msdn

-1

??是空合併運算符

讀到它在這裏: link text

+0

Downvote因爲沒有解釋

X = (if Y is not null return Y) ?? (else return DEFAULT) 

讀取詳細的討論。 – problemofficer 2016-05-19 23:00:00

4

?? Operator (C# Reference)

的?運算符稱爲 空合併運算符,並且使用 來定義空值類型以及 引用類型的默認值。如果它不爲空,則返回 左側的操作數; 否則返回正確的 操作數。

你的實例可以被重新寫爲:

public NameValueCollection Metadata 
    { 
    get { 
      if (metadata == null) 
       metadata = new NameValueCollection(); 

      return metadata; 
     } 
    } 
2

從MSDN:http://msdn.microsoft.com/en-us/library/ms173224.aspx

甲空類型可以包含值,或者它可以是不明確的。 ?? ??運算符定義將可空類型分配給非空類型時要返回的默認值。如果您嘗試將空值類型分配給非空值類型而不使用?運算符,則會生成編譯時錯誤。如果您使用強制轉換,並且可以爲空的值類型當前未定義,則將引發InvalidOperationException異常。

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

}

+0

如果您要引用MSDN,請提供鏈接。 – strager 2010-08-07 16:06:56