C# 中的三元运算符
使用三元运算符,可以执行如下操作(假设 Func1() 和 Func2() 返回一个 int:
int x = (x == y) ? Func1() : Func2();
但是,有没有办法在不返回值的情况下执行相同的操作?例如,类似 (假设 Func1() 和 Func2() 返回 void):
(x == y) ? Func1() : Func2();
我意识到这可以使用 if 语句来完成,我只是想知道是否有办法这样做。
With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int:
int x = (x == y) ? Func1() : Func2();
However, is there any way to do the same thing, without returning a value? For example, something like (assuming Func1() and Func2() return void):
(x == y) ? Func1() : Func2();
I realise this could be accomplished using an if statement, I just wondered if there was a way to do it like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
很奇怪,但你可以做
Weird, but you could do
我不这么认为。据我记得,三元运算符用于表达式上下文,而不是用作语句。 编译器需要知道表达式的类型,而
void
并不是真正的类型。您可以尝试为此定义一个函数:
然后您可以这样调用它:
但这并不能真正使您的代码更清晰......
I don't think so. As far as I remember, the ternary operator is used in an expression context and not as a statement. The compiler needs to know the type for the expression and
void
is not really a type.You could try to define a function for this:
And then you could call it like this:
But this does not really make your code any clearer...
如果您有信心,您可以创建一个静态方法,其唯一目的是吸收表达式并“使其成为”一条语句。
通过这种方式,您可以调用三元运算符并调用其扩展方法。
或者,以几乎等效的方式,编写静态方法(如果要使用此“快捷方式”的类受到限制)。
...并以这种方式调用它
但是,我强烈建议不要使用这个“快捷方式”,原因与我之前的作者已经明确指出的相同。
If you feel confident, you'd create a static method whose only purpose is to absorb the expression and "make it" a statement.
In this way you could call the ternary operator and invoke the extension method on it.
Or, in an almost equivalent way, writing a static method (if the class when you want to use this "shortcut" is limited).
... and calling it in this way
However I strongly reccomend to not use this "shortcut" for same reasons already made explicit by the authors before me.
不,因为三元运算符是表达式,而 actions/void 函数是语句。您可以让它们返回
object
,但我认为 if/else 块将使意图更加清晰(即,执行操作是为了它们的副作用而不是它们的值)。No, because the ternary operator is an expression, whereas actions/void functions are statements. You could make them return
object
, but I think that an if/else block would make the intent much clearer (i.e. the actions are being executed for their side-effects instead of their values).