.NET: Inferred generic types on static methods

前端 未结 5 1129
失恋的感觉
失恋的感觉 2020-12-29 09:18

Suppose I have

public static List Map(List inputs, Func f)
{
    return inputs.ConvertAll((x) => f(x));
}

pr         


        
5条回答
  •  感情败类
    2020-12-29 09:37

    From your error message:

    The type arguments for method '[...].Map(System.Collections.Generic.List, System.Func)' cannot be inferred from the usage. Try specifying the type arguments explicitly.

    Note that the error message says that it can not figure out the type arguments. That is, it is having trouble resolving one of the type parameters T or T2. This is because of §25.6.4 (Inference of type arguments) of the specification. This is the part of the specification the deals with inferring generic type parameters.

    Nothing is inferred from the argument (but type inference succeeds) if any of the following are true:

    [...]

    The argument is a method group.

    Thus, the compiler is not able to use the delegate type of Square to infer the type of T2. Note that if you change the declaration to

    public static List Map(List inputs, Func f) {
            return inputs.ConvertAll((x) => f(x));
    }
    

    then

    var outputs = Map(inputs, Square);
    

    is legal. In this case, it has already resolved that T is int from the fact that inputs is a List.

    Now, the deeper question is why is the above the specification? That is, why don't method groups play a role in type parameter resolution? I think it's because of cases like this:

    class Program {
        public static T M(Func f) {
            return default(T);
        }
    
        public static int F(int i) {
            return i;
        }
    
        public static float F(float f) {
            return f;
        }
    
        static void Main(string[] args) {
            M(F); // which F am I?
        }
    }
    

提交回复
热议问题