Law*_*ton 5 c# lambda overloading method-group
// Compiler Error当在所有其他情况下正确推断出类型时,为什么不能在下面的代码中标记的行上推断出要调用的正确重载?
public static class Code {
private static void Main() {
OverloadedMethod<string>(() => new Wrapper<string>()); // OK
OverloadedMethod<string>(() => MethodReturningWrappedString()); // OK
OverloadedMethod<string>((Func<Wrapper<string>>)MethodReturningWrappedString); // OK
OverloadedMethod<string>(MethodReturningWrappedString); // Compiler Error
}
public static Wrapper<string> MethodReturningWrappedString() {
return new Wrapper<string>();
}
public static void OverloadedMethod<T>(Func<Wrapper<T>> func) where T : class {
}
public static void OverloadedMethod<T>(Func<T> func) where T : class {
}
public struct Wrapper<T> where T : class {
}
}
Run Code Online (Sandbox Code Playgroud)
这是编译器错误:
The call is ambiguous between the following methods or properties:
'Namespace.Code.OverloadedMethod<string>(System.Func<Namespace.Code.Wrapper<string>>)'
and 'Namespace.Code.OverloadedMethod<string>(System.Func<string>)'
Run Code Online (Sandbox Code Playgroud)
因为方法组MethodReturningWrappedString既可以转换为类型的委托,也可以转换为和的合适值的Func<Wrapper<T>>类型的委托。Func<U>TU
重载解析规则并未规定第一个转换严格优于第二个转换,因此转换不明确并导致编译器错误。