Ternary operators in C#

后端 未结 4 893
你的背包
你的背包 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 18:58

    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");
        }
    }
    
    0 讨论(0)
  • 2020-12-16 19:03

    No, because the ternary operator is an expression, whereas actions/void functions are statements. You could make them return object, but I think that an if/else block would make the intent much clearer (i.e. the actions are being executed for their side-effects instead of their values).

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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...

    0 讨论(0)
提交回复
热议问题