.NET: Inferred generic types on static methods

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

Suppose I have

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

pr         


        
5条回答
  •  旧时难觅i
    2020-12-29 09:37

    The reason this does not work is for c# to do type inference on a method, it has to know the delegate type at the other end of the conversion. But at this point in time, the target delegate type is still not fully known - only T (int) is known, T2 is still unresolved.

    Func f = Square;
    //works because we provided the destination type
    //of the conversion from Square to delegate
    
    Map(inputs, i => Square(i));
    //works because the lambda follows the actual method call
    //and determines its own return type
    

提交回复
热议问题