Why doesn't C# infer my generic types?

后端 未结 7 1754
小鲜肉
小鲜肉 2020-11-22 16:38

I\'m having lots of Funcy fun (fun intended) with generic methods. In most cases C# type inference is smart enough to find out what generic arguments it must use on my gener

7条回答
  •  失恋的感觉
    2020-11-22 17:06

    The spec lays this out pretty clearly:

    Section 7.4.2 Type Inference

    If the supplied number of arguments is different than the number of parameters in the method, then inference immediately fails. Otherwise, assume that the generic method has the following signature:

    Tr M(T1 x1 … Tm xm)

    With a method call of the form M(E1 …Em) the task of type inference is to find unique type arguments S1…Sn for each of the type parameters X1…Xn so that the call M(E1…Em)becomes valid.

    As you can see, the return type is not used for type inference. If the method call does not map directly to the type arguments inference immediately fails.

    The compiler does not just assume that you wanted string as the TResult argument, nor can it. Imagine a TResult derived from string. Both would be valid, so which to choose? Better to be explicit.

提交回复
热议问题