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

ric*_*lla 6 c# delegates compiler-errors ambiguous

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

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,运行此代码会调用"方法"的第二个重载,即期望返回任务的函数委托.但是,如果我更改代码以避免在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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

Joe*_*ung 1

长答案位于/sf/answers/144119811/(正如 richzilla 指出的那样)。

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

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


归档时间:

查看次数:

647 次

最近记录:

11 年,1 月 前