2010-09-24 83 views
1

試圖弄清楚如何讓null合併運算符在foreach循環中工作。在foreach語句中使用null合併

我在檢查一下字符串以什麼結尾,並基於它,將它路由到某個方法。基本上我想說的是....

foreach (String s in strList) 
{ 
    if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type"; 
} 

在試圖做到這一點,當然你「操作??不能在布爾類型和字符串類型使用。」我知道還有其他方法可以做到,只是想看看如何使用空合併完成它。

週末愉快。

@Richard Ev:哦,當然是。開關,如果其他,等等。只是好奇它是如何可以處理的

@Jon Skeet:看完你的評論後,它打我,這是不好的!我對 基本上對兩個文件擴展名感興趣。如果一個文件以「abc」結尾爲 實例,發送到方法1,如果文件以「xyz」結尾發送到方法2.但是 如果文件以「hij」的擴展名結束,那麼該怎麼辦? '重做。

感謝Brian和GenericTypeTea以及對thoughful輸入

我含量調用它關閉。

+2

做**有空合併運算符是什麼**?你的例子沒有意義。這意味着什麼? – 2010-09-24 15:05:12

+1

真的不清楚你想要做什麼。如果你可以用不同的方式寫(但使用有效的代碼),我們可能會提供幫助。我們不知道Method1或Method2做了什麼,或者你想對字符串「未知文件類型」做什麼。 – 2010-09-24 15:05:37

+0

重要的是要注意,你沒有將該語句的結果分配給任何東西。目前您所擁有的將評估爲Method1的返回類型或方法2的返回類型,或字符串「未知文件類型」,但您沒有對結果進行任何操作。某處需要對變量進行賦值。 – 2010-09-24 15:11:12

回答

1

我認爲編譯器給了你適當的答案,你不能。

空合併基本上是這個if語句:

if(x == null) 
    DoY(); 
else 
    DoZ(); 

一個布爾值,不能爲空,所以你不能合併會這樣。我不確定您的其他方法會返回什麼結果,但您似乎希望在此處使用簡單的||運算符。

8

它看起來像你想使用正常的三元運算符,而不是空合併。喜歡的東西:

string result; 
if (s.EndsWith("d")) 
    result = Method1(s); 
else 
    result = Method2(s); 
if (result == null) 
    result = "Unknown file type"; 
return result; 
+0

這將取決於Method1和Method2都能夠返回null(即,ref類型不是值類型) – Funka 2010-09-24 15:37:24

+0

@Funka,''''操作符的結果類型是一個'string',所以我認爲它對Bob來說是安全的假設'Method1'和'Method2'也返回'string'。 – JaredPar 2010-09-24 16:18:17

3

我想你想的條件(三元)運算符的組合和空合併運算符:

foreach (String s in strList) 
{ 
    string result = (s.EndsWith("d") ? Method1(s) : Method2(s)) 
     ?? "Unknown file type"; 
} 

簡單

(s.EndsWith("d") ? Method1(s) : Method2(s)) ?? "Unknown file type"; 

到這相當於英語,這將執行以下操作:

If s ends with d, then it will try Method1. 
If s does not end with d then it will try Method2. 
Then if the outcome is null, it will use "Unknown file type" 
If the outcome is not null, it will use the result of either A or B 
0

您應該首先使用??空合併運算符來防範null引用。然後用?三元運算符在Method1Method2之間進行選擇。最後再次使用??空合併運算符來提供默認值。

foreach (string s in strList) 
{ 
    string computed = s; 
    computed = computed ?? String.Empty; 
    computed = computed.EndsWith("d") ? Method1(s) : Method2(s); 
    computed = computed ?? "Unknown file type"; 
}