Why doesn't the C# ternary operator work with delegates?

后端 未结 2 1630
时光取名叫无心
时光取名叫无心 2020-12-01 20:40

When branching to select a function, it might make sense to use the ternary operator to select a function, but this is impossible. Why?

public class Demo {
         


        
2条回答
  •  离开以前
    2020-12-01 21:33

    The problem is that demo1 is not a simple expression, it is a method. And methods can be overriden, so it is not actually one method, it is a method group. Consider the following example:

    public class Demo {
        protected bool branch;
        protected void demo1 (int) {}
        protected void demo1 () {}
        protected void demo2 () {}
        public Action DoesntWork() {
            return branch ? demo1 : demo2; //Error
            return demo1; //ok
        }
    }
    

    Now, demo1 is overloaded, so which one of the two versions should be used? The answer is that the overloaded function is selected by using the context in which the function is used.

    In the return demo1 it is obvious, it expects an Action.

    But in the return branch? demo1 : demo2; the context is not so easy. The ternary operator first tries to match the type of demo1 with that of demo2, but that is another method group so there is no help there. The compiler does not look beyond and fails.

    The solution is to make clear the type expected from the method group:

    return branch? new Action(demo1) : demo2;
    
    return branch? (Action)demo1 : demo2;
    
    Action d1 = demo1;
    return branch? d1 : demo2;
    

提交回复
热议问题