Why does “Func test = value ? F: F” not compile?

后端 未结 2 1759
借酒劲吻你
借酒劲吻你 2020-12-06 09:56

I have seen similar questions to this, but they involve different types so I think this is a new question.

Consider the following code:

public void T         


        
相关标签:
2条回答
  • 2020-12-06 10:12
    var test = value ? (Action)Func: (Action)Func;
    

    Actually, type of method is expressed by delegate it matches. System.Action that i used to cast methods to, is the delegate with signature returning void and taking no parameters - it matches your Func() method. And now your test will know that it is type of System.Action. Delegates are something like interfaces for methods. Take a look at http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx

    0 讨论(0)
  • 2020-12-06 10:15

    The question was changed significantly, so my original answer is a bit off by now.

    However, the problem is essentially the same. I.e. there could be any number of matching delegate declarations for F and since there is no implicit conversion between two identical delegate declarations the type of F cannot be converted to Func<bool>.

    Likewise, if you declare

    private delegate void X();
    private delegate void Y();
    private static void Foo() {}
    

    You cannot do

    X x = Foo;
    Y y = x;
    

    Original answer:

    It doesn't work because method groups cannot be assigned to an implicitly typed variable.

    var test = Func; doesn't work either.

    The reason being that there could be any number of delegate types for Func. E.g. Func matches both of these declarations (in addition to Action)

    private delegate void X();
    private delegate void Y();
    

    To use implicitly typed variables with method groups, you need to remove the ambiguity by casting.


    See archil's answer for a concrete example of one way to fix this. That is, he shows what the corrected code might look like [assuming the delegate you desire to match is Action].

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