[英]Ternary operators in C#
With the ternary operator, it is possible to do something like the following (assuming Func1() and Func2() return an int: 使用三元运算符,可以执行以下操作(假设Func1()和Func2()返回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):
例如,类似(假设Func1()和Func2()返回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. 我意识到这可以使用if语句来完成,我只是想知道是否有办法像这样做。
Weird, but you could do 很奇怪,但你可以做到
class Program
{
private delegate void F();
static void Main(string[] args)
{
((1 == 1) ? new F(f1) : new F(f2))();
}
static void f1()
{
Console.WriteLine("1");
}
static void f2()
{
Console.WriteLine("2");
}
}
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. 编译器需要知道表达式的类型,而
void
实际上不是一个类型。
You could try to define a function for this: 您可以尝试为此定义一个函数:
void iif(bool condition, Action a, Action b)
{
if (condition) a(); else b();
}
And then you could call it like this: 然后你可以这样称呼它:
iif(x > y, Func1, Func2);
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. 如果您有信心,那么您将创建一个静态方法,其唯一目的是吸收表达式并“使其成为”语句。
public static class Extension
{
public static void Do(this Object x) { }
}
In this way you could call the ternary operator and invoke the extension method on it. 通过这种方式,您可以调用三元运算符并在其上调用扩展方法。
((x == y) ? Func1() : Func2()).Do();
Or, in an almost equivalent way, writing a static method (if the class when you want to use this "shortcut" is limited). 或者,以几乎相同的方式,编写静态方法(如果您想使用此“快捷方式”的类是有限的)。
private static void Do(object item){ }
... and calling it in this way ......并以这种方式调用它
Do((x == y) ? Func1() : Func2());
However I strongly reccomend to not use this "shortcut" for same reasons already made explicit by the authors before me. 但是我强烈建议不要使用这个“捷径”,原因与我之前作者已经明确说明的原因相同。
No, because the ternary operator is an expression, whereas actions/void functions are statements. 不,因为三元运算符是表达式,而actions / void函数是语句。 You could make them return
object
, but I think that an if/else block would make the intent much clearer (ie the actions are being executed for their side-effects instead of their values). 你可以让它们返回
object
,但我认为if / else块会使意图更加清晰(即正在为其副作用而不是它们的值执行动作)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.