2010-09-24 29 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"; 
}