【发布时间】:2021-08-20 08:52:34
【问题描述】:
在尝试新概念时,我发现了Ternary Operator 及其美丽之处。玩了一段时间后,我决定测试一下它的极限。
但是,当我无法编译某行代码时,我的乐趣很快就结束了。
int a = 5;
int b = 10;
a == b ? doThis() : doThat()
private void doThis()
{
MessageBox.Show("Did this");
}
private void doThat()
{
MessageBox.Show("Did that");
}
这一行给了我两个错误:
Error 1 Only assignment, call, increment, decrement, and new object expressions can be used as a statement
Error 2 Type of conditional expression cannot be determined because there is no implicit conversion between 'void' and 'void'
我从来没有使用过Ternary Operator 来决定调用哪个方法,我也不知道它是否可行。我只是喜欢使用单行 If Else Statement 进行方法调用的想法。
我做了一些研究,但找不到任何人这样做的例子,所以我想我可能希望有一些不可能的事情。
如果可以的话,请指教我的错误做法,不可以,有没有别的办法?
【问题讨论】:
-
确保函数 doThis 和 doThat 返回一个 int 类型的值。
-
如果你真的想要一行
If Else,就写成一行:if (condition) doThis(); else doThat();并不总是一件好事。