1

试图弄清楚如何让 null 合并运算符在 foreach 循环中工作。

我正在检查字符串以什么结尾,并在此基础上将其路由到某个方法。基本上我想说的是......

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

在尝试执行此操作时,您当然会得到“运算符 ?? 不能用于 bool 类型和字符串类型”。我知道还有其他方法可以做到这一点,只是想看看如何通过空合并来完成。

有一个美好的周末。

@Richard Ev:哦,当然。Switch,if else等。只是好奇如何处理

@Jon Skeet:读了你的评论后,我觉得这很糟糕!我基本上对两个文件扩展名感兴趣。例如,如果文件以“abc”结尾,则发送到方法 1,如果文件以“xyz”结尾,则发送到方法 2。但是如果文件以“hij”的扩展名结尾怎么办......繁荣,你完毕。

感谢 Brian 和 GenericTypeTea 的周到输入

我很满足称它为关闭。

4

4 回答 4

8

It looks like you want to use the normal ternary operator, not null coalescing. Something like:

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

This is equivalent to:

string result;
if (s.EndsWith("d"))
  result = Method1(s);
else
  result = Method2(s);
if (result == null)
  result = "Unknown file type";
return result;
于 2010-09-24T15:06:45.577 回答
3

I think you want a combination of the conditional (ternary) operator and the null coalescing operator:

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

In simple english, this will do the following:

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
于 2010-09-24T15:07:11.207 回答
1

我认为编译器给了你适当的答案,你不能。

空值合并本质上是这个 if 语句:

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

布尔值不能为空,所以你不能像那样合并它。我不确定您的其他方法返回什么,但您似乎想要一个简单的||运算符。

于 2010-09-24T15:06:08.803 回答
0

您应该首先使用??空合并运算符来防止空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";
}
于 2010-09-24T15:35:43.610 回答