【问题标题】:Ambiguous C# method call with delegates [duplicate]带有委托的模棱两可的 C# 方法调用 [重复]
【发布时间】:2015-08-27 08:17:58
【问题描述】:

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

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();
        }
    }

正如预期的那样,运行此代码会调用“方法”的第二个重载,它需要一个返回任务的函数委托。但是,如果我更改代码以避免在 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# 编译器现在抱怨我对“方法”的调用不明确。我错过了什么?

【问题讨论】:

  • 您没有将 Uri 传递给 Method2。
  • @SamAxe 他不是故意的。他正在尝试将 方法组 (Method2) 转换为委托 (Func&lt;Uri, Task&lt;Uri&gt;&gt;)
  • 可能是因为Func&lt;in T, out TResult&gt;中的TResult是协变的。
  • @M.kazemAkhgary,ReSharper 建议解决歧义。问题是为什么会有歧义,因为显然没有从 Func&lt;Uri, Uri&gt;Method2 的隐式转换。
  • @richzilla 这确实是个骗局,答案就在这里:“这里的原则是,确定方法组可转换性需要使用重载解析从方法组中选择一个方法,并且 重载解析不考虑返回类型。”

标签: c# compiler-errors delegates ambiguous


【解决方案1】:

长答案是https://stackoverflow.com/a/2058854/1223597(正如richzilla 指出的那样)。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-13
    • 2011-03-27
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    相关资源
    最近更新 更多