带有委托的不明确的 C# 方法调用

Ambiguous C# method call with delegates

在我的应用程序中,我有类似于以下的代码:

class Program
    {
        static void Main(string[] args)
        {
            Method(uri => Task.FromResult(uri));
        }

        static void Method(Func<Uri, Uri> transformer)
        {
            throw new NotImplementedException();
        }

        static void Method(Func<Uri, Task<Uri>> transformer)
        {
            throw new NotImplementedException();
        }
    }

正如预期的那样,运行 此代码调用了 'Method' 的第二个重载,该代码期望 returns 任务的函数委托。但是,如果我更改代码以避免在 Main:

中使用匿名方法
class Program
    {
        static void Main(string[] args)
        {
            Method(Method2);
        }

        static Task<Uri> Method2(Uri uri)
        {
            return Task.FromResult(uri);
        }

        static void Method(Func<Uri, Uri> transformer)
        {
            throw new NotImplementedException();
        }

        static void Method(Func<Uri, Task<Uri>> transformer)
        {
            throw new NotImplementedException();
        }
    }

C# 编译器现在抱怨我对 'Method' 的调用不明确。我错过了什么?

长答案在 (正如 richzilla 指出的那样)。

简短的回答是 C# 编译器团队选择进行方法组转换(如 Method(Method2))忽略 return 类型(此处为 Method2)。这使他们可以灵活地解析 Expression 树。不幸的是,这意味着编译器无法在您的 2 Method 签名之间隐式选择。

在进行 lambda 转换时,(Method(uri => Task.FromResult(uri))),编译器团队无需担心表达式树解析,因此他们考虑return 类型。