Why is C# unable to infer the generic type argument type from a non-generic static method's signature?

后端 未结 2 2250
予麋鹿
予麋鹿 2021-02-19 22:36

I have conducted the following inference tests:

static class InferenceTest {
    static void TakeInt(int a) { }
    static int GiveInt() { return 0; }
    static         


        
相关标签:
2条回答
  • 2021-02-19 23:07

    Method parameters are not inspected.

    As suggested, in ConsumeFunc1Func2 the compiler is inferring only from return values. In ConsumeFunc2c, TakeAndGiveInt signature is not inspected to see if its method parameter type is actually of the same type of the method return type cause... method parameters are not inspected!

    0 讨论(0)
  • 2021-02-19 23:18

    In general, a method name will not uniquely identify a unique type Action<T> to which the method group could be assigned. For example, even if there's only one overload of Fred and it takes a single Cat argument, that overload could be assigned not just to an Action<Cat>, but also to some other types like Action<Mammal>, Action<Animal>, or Action<Object>. While there are some cases where one type substitution would be in every way superior to any alternative, that is not always the case. It's cleaner to define the language to require that the type of delegate be specified, than to have the compiler try to "guess", especially since having the compiler guess would mean that many things which shouldn't be breaking changes, would be (e.g. adding a method overload may render ambiguous a type inference which used to work).

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