Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在lambda中调用方法时,为什么将方法组传递给重载方法会导致歧义?在这种情况下,lambda不会这样做?_C#_Lambda_Overloading_Method Group - Fatal编程技术网

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:很好,但是方法组的委托转换没有考虑到这一点。