在 foreach 语句中使用 null 合并
试图找出如何让空合并运算符在 foreach 循环中工作。
我正在检查字符串以什么结尾,并基于此将其路由到某个方法。基本上我想说的是......
foreach (String s in strList)
{
if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type";
}
在尝试执行此操作时,您当然会得到“运算符??不能用于布尔类型和字符串类型。”我知道还有其他方法可以做到这一点,只是想看看如何通过空合并来完成它。
有一个美好的周末。
@Richard Ev:哦,当然。 Switch,if else 等等。只是好奇它是如何实现的 可以处理
@Jon Skeet:读完你的评论后,我震惊了,这太糟糕了!我是 基本上对两个文件扩展名感兴趣。如果文件以“abc”结尾 例如,发送到方法 1,如果文件以“xyz”结尾,则发送到方法 2。但是 如果文件以“hij”扩展名结尾怎么办...繁荣,你就完成了。
感谢 Brian 和 GenericTypeTea 的深思熟虑,
我很高兴称其已关闭。
Trying to figure out how to get the null coalescing operator to work in a foreach loop.
I'm checking to see what a string ends with and based on that, route it to a certain method. Basically what I want to say is....
foreach (String s in strList)
{
if s.EndsWith("d") ?? Method1(s) ?? Method2(s) ?? "Unknown file type";
}
In attempting to do this, of course you get the "Operator ?? cannot be used on type bool and type string." I know there is other ways to do it, just want to see how it can be done with null coalescing.
Have a good weekend.
@Richard Ev: Oh yes of course. Switch, if else, etc. Was just curious how it
could be handled
@Jon Skeet: After reading your comments it hit me, this is just bad! I am
interested in two file extensions basically. If a file ends with "abc" for
instance, send to method 1, if the file ends with "xyz" send to method 2. But
what if a file ends with an extension of "hij"...boom, you're done.
Thanks to Brian and GenericTypeTea as well for the thoughful input
I'm content calling it closed.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
看起来您想使用普通的三元运算符,而不是空合并。类似于:
这相当于:
It looks like you want to use the normal ternary operator, not null coalescing. Something like:
This is equivalent to:
我认为你想要条件(三元)运算符和空合并运算符的组合:
用简单的英语来说,这将执行以下操作:
I think you want a combination of the conditional (ternary) operator and the null coalescing operator:
In simple english, this will do the following:
我认为编译器给了你适当的答案,但你不能。
空合并本质上是这样的 if 语句:
布尔值不能为空,因此您不能像那样合并它。我不确定您的其他方法返回什么,但您似乎需要一个简单的
||
运算符。I think the compiler gave you the appropriate answer, you can't.
Null coalescing is essentially this if statement:
A boolean value cannot be null, so you can't coalesce it like that. I'm not sure what your other methods return, but it seems like you want a simple
||
operator here.您应该首先使用
??
null 合并运算符来防止 nulls
引用。然后使用?
三元运算符在Method1
和Method2
之间进行选择。最后再次使用??
null 合并运算符来提供默认值。You should first use the
??
null coalescing operator to guard against a nulls
reference. Then use the?
ternary operator to choose betweenMethod1
andMethod2
. Finally use the??
null coalescing operator again to provide the default value.