三元表达可能吗? [英] Ternary Expression Possible?
本文介绍了三元表达可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道,如果下面的语句可以写成一行(即三元形式)。
I'm not sure if the following statement is possible to write as one line (i.e. Ternary form).
if (A == B)
FunctionA();
else
FunctionB();
泛函和FunctionB两者都是void类型。
Both FunctionA and FunctionB are type void.
推荐答案
没有。条件运算符是仅适用于的非空的表达式。 。写在如果
No. The conditional operator is only valid for non-void expressions. The point is to evaluate one of two expressions, and for that to be the result.
基本上>语句。这是执行一个的动作的或其他
Basically: write the if
statement. It's the idiomatic way of executing one action or another.
您的的惯用方式可以的写一个像这样的扩展方法:。
You could write an extension method like this:
// For demonstration purposes only. Please don't use in real life.
public static void Conditional(this bool result,
Action trueAction,
Action falseAction)
{
Action action = result ? trueAction : falseAction;
action();
}
然后:
Then:
(A == B).Conditional(FunctionA, FunctionB);
...但我的强烈的劝你还是不要。
这篇关于三元表达可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文