.NET: Inferred generic types on static methods

前端 未结 5 1151
失恋的感觉
失恋的感觉 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:48

    The inference fails at inferring the type of the delegate, not the list:

    // this is also fine
    var outputs3 = Map(inputs, new Func(Square));
    
    // more calls that compile correctly
    var outputs4 = Map(inputs, x => Square(x));
    
    var outputs5 = Map(inputs, x => x * x);
    
    Func t = Square;
    var outputs6 = Map(inputs, t);
    

    I don't know why, though - perhaps there's just no implicit typecast from the signature of Square to Func? It seems strange that Func t = Square; is valid, but the compiler can't make the leap on its own... Bug, maybe?

提交回复
热议问题