C# 在lambda中调用方法时,为什么将方法组传递给重载方法会导致歧义?在这种情况下,lambda不会这样做?
当在所有其他情况下正确推断类型时,为什么不能在下面代码中标记为C# 在lambda中调用方法时,为什么将方法组传递给重载方法会导致歧义?在这种情况下,lambda不会这样做?,c#,lambda,overloading,method-group,C#,Lambda,Overloading,Method Group,当在所有其他情况下正确推断类型时,为什么不能在下面代码中标记为//Compiler Error的行上推断要调用的正确重载 public static class Code { private static void Main() { OverloadedMethod<string>(() => new Wrapper<string>()); // OK OverloadedMethod<string>(() =
//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 {
}
}
公共静态类代码{
私有静态void Main(){
重载方法(()=>newwrapper());//确定
重载方法(()=>MethodReturningWrappedString());//确定
重载方法((Func)MethodReturningWrappedString);//确定
重载方法(MethodReturningWrappedString);//编译器错误
}
公共静态包装器方法ReturningWrappedString(){
返回新包装器();
}
公共静态void重载方法(Func Func),其中T:class{
}
公共静态void重载方法(Func Func),其中T:class{
}
公共结构包装器,其中T:class{
}
}
以下是编译器错误:
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>)'
以下方法或属性之间的调用不明确:
'Namespace.Code.重载方法(System.Func)'
和“Namespace.Code.重载方法(System.Func)”
因为方法组MethodReturningWrappedString
可以转换为Func
类型的委托和Func
类型的委托,以获得合适的T
和U
值
重载解析规则没有规定第一次转换严格优于第二次转换,因此转换不明确并导致编译器错误。lambda“()=>MethodReturningWrappedString()是否那么,使用不同的规则?那么,为什么在传递lambda时要考虑通用约束
where T:class
,而在传递方法组时不考虑它呢?但是Wrapper
是一个结构,所以它不能满足Func where U:class
@Craig:在这种情况下,调用method
--只有一个重载,所以选择了它。@mikez:很好,但是方法组的委托转换没有考虑到这一点。