[英]Using null coalescing in foreach statement
試圖弄清楚如何使空合並運算符在foreach循環中工作。
我正在檢查字符串以什么結尾,並以此為基礎,將其路由到特定方法。 基本上我想說的是...
foreach (String s in strList)
{
if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type";
}
嘗試執行此操作時,您當然會得到“不能在bool類型和string類型上使用運算符??”。 我知道還有其他方法可以做到,只是想看看如何通過空合並實現。
周末愉快。
@Richard Ev:當然可以。 切換,如果還有其他,等等。只是好奇如何處理
@Jon Skeet:在讀完您的評論后,我很震驚,這真是太糟糕了! 我基本上對兩個文件擴展名感興趣。 例如,如果文件以“ abc”結尾,則發送至方法1,如果文件以“ xyz”結尾,則發送至方法2。但是,如果文件以擴展名“ hij”結尾...該怎么辦?完成。
也感謝Brian和GenericTypeTea的寶貴意見
我很滿意將其關閉。
看起來您想使用普通的三元運算符,而不是null合並。 就像是:
(s.EndsWith("d") ? Method1(s) : Method2(s)) ?? "Unknown file type";
這等效於:
string result;
if (s.EndsWith("d"))
result = Method1(s);
else
result = Method2(s);
if (result == null)
result = "Unknown file type";
return result;
我認為您需要條件(三元)運算符和空合並運算符的組合:
foreach (String s in strList)
{
string result = (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
我認為編譯器給了您適當的答案,您不能。
空合並本質上是以下if語句:
if(x == null)
DoY();
else
DoZ();
布爾值不能為null,因此不能像這樣將其合並。 我不確定其他方法會返回什么,但似乎您想要一個簡單的||
操作員在這里。
您應該先使用??
空合並運算符,以防范空s
參考。 然后用?
三元運營商之間進行選擇Method1
和Method2
。 最后用??
再次使null合並運算符提供默認值。
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";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.