Ternary operators in C#

后端 未结 4 903
你的背包
你的背包 2020-12-16 18:30

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(         


        
4条回答
  •  轮回少年
    2020-12-16 19:24

    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:

    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...

提交回复
热议问题