Ternary operators in C#

后端 未结 4 896
你的背包
你的背包 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条回答
  •  -上瘾入骨i
    2020-12-16 19:15

    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.

提交回复
热议问题