问题描述
注意:我之前曾经看过这个问题( a , b , c ),但这些都不是在C#中也无济于事.
Note: I've seen this question asked sometimes before (a, b, c), but neither of these was in C#, nor helpful.
假设我正在使用?:
这样的三元运算符(在 false
情况下不执行任何操作):
Assume I'm using the ? :
ternary operator like this (to do nothing when false
is the case):
r==5? r=0 : <nothing> ;
我遇到一个错误.在此放置一些东西显然可以解决问题.我该如何在不做任何随机空函数的情况下让另一端保持空状态?
I'm getting an error. Putting something there will obviously solve the problem.How can I still keep the other side empty without making some random empty function?
推荐答案
您不能.条件?:运算符的全部要点是它对 expression 求值.您甚至不能只使用:
You can't. The whole point of the conditional ?: operator is that it evaluates an expression. You can't even just use:
Foo() ? Bar() : Baz();
...因为这不是声明.您必须对结果做些事情...例如,就像访问属性一样.
... because that isn't a statement. You have to do something with the result... just like when you access a property, for example.
如果只想在满足特定条件时才执行一段代码,则?:运算符不是您想要的-您需要 if
语句:
If you want to only execute a piece of code when a specific condition is met, the ?: operator isn't what you want - you want an if
statement:
if (foo)
{
bar();
}
就这么简单.请勿试图将条件运算符扭曲为原本不应该的东西.
It's as simple as that. Don't try to twist the conditional operator into something it's not meant to be.
这篇关于当“另一侧"发生时,不执行任何操作三元运算符到达?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!