C#中兩個問號共贊成味着什麼?

跨越這行代碼: 數據結構

FormsAuth = formsAuth ?? new FormsAuthenticationWrapper();

這兩個問號意味着什麼,是某種三元運算符? 谷歌很難找到。 app


#1樓

若是你熟悉Ruby,它的||=彷佛相似於C#的?? 對我來講。 這是一些Ruby: ide

irb(main):001:0> str1 = nil
=> nil
irb(main):002:0> str1 ||= "new value"
=> "new value"
irb(main):003:0> str2 = "old value"
=> "old value"
irb(main):004:0> str2 ||= "another new value"
=> "old value"
irb(main):005:0> str1
=> "new value"
irb(main):006:0> str2
=> "old value"

在C#中: 測試

string str1 = null;
str1 = str1 ?? "new value";
string str2 = "old value";
str2 = str2 ?? "another new value";

#2樓

這沒什麼危險的。 事實上,它是美麗的。 若是須要,您能夠添加默認值,例如: spa

code

int x = x1 ?? x2 ?? x3 ?? x4 ?? 0;

#3樓

在此輸入圖像描述

兩個問號(??)表示它是一個Coalescing運算符。 orm

Coalescing運算符返回鏈中的第一個NON-NULL值。 你能夠看到這個youtube視頻 ,它實際上展現了整個事物。 視頻

可是,讓我爲視頻所說的內容添加更多內容。 對象

若是你看到合併的英文含義,就說「合併在一塊兒」。 例如,下面是一個簡單的合併代碼,它連接了四個字符串。 索引

所以,若是str1null ,它將嘗試str2 ,若是str2null ,它將嘗試str3 ,依此類推,直到找到具備非null值的字符串。

string final = str1 ?? str2 ?? str3 ?? str4;

簡單來講,Coalescing運算符從鏈中返回第一個NON-NULL值。


#4樓

這裏使用合併獲取值的一些示例是低效的。

你真正想要的是:

return _formsAuthWrapper = _formsAuthWrapper ?? new FormsAuthenticationWrapper();

要麼

return _formsAuthWrapper ?? (_formsAuthWrapper = new FormsAuthenticationWrapper());

這能夠防止每次都從新建立對象。 而不是私有變量保持爲null而且在每一個請求上建立新對象,這確保在建立新對象時分配私有變量。


#5樓

正如許多答案中正確指出的那樣是「空合併運算符」( ?? ),說到你也可能想要查看它的表兄「Null-conditional Operator」( ?。?[ ),它是一個運算符不少次它與??一塊兒使用

空條件運算符

用於在執行成員訪問( ?。 )或索引( ?[ )操做以前測試null。 這些運算符可幫助您編寫更少的代碼來處理空值檢查,尤爲是降序到數據結構中。

例如:

// if 'customers' or 'Order' property or 'Price' property  is null,
// dollarAmount will be 0 
// otherwise dollarAmount will be equal to 'customers.Order.Price'

int dollarAmount = customers?.Order?.Price ?? 0;

舊的方式沒有?? 作到這一點

int dollarAmount = customers != null 
                   && customers.Order!=null
                   && customers.Order.Price!=null 
                    ? customers.Order.Price : 0;

這更冗長,更麻煩。

相關文章
相關標籤/搜索