为什么不C#的Func键℃至重载工作; T,T>和行动< T&GT ;? [英] Why doesn't C#'s overload resolution work between Func<T,T> and Action<T>?

查看:117
本文介绍了为什么不C#的Func键℃至重载工作; T,T>和行动< T&GT ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,IEnumerable的,运行一个相当普遍的扩展方法:

So, a fairly common extension method for IEnumerable, Run:

public static IEnumerable<T> Run<T>(this IEnumerable<T> source, Action<T> action)
{
    foreach (var item in source)
    {
        action(item);
        yield return item;
    }
}

当我尝试使用与,例如, DbSet.Add:

When I try to use that with, for instance, DbSet.Add:

invoice.Items.Run(db.InvoiceItems.Add);
// NB: Add method signature is
// public T Add(T item) { ... }

...编译器会抱怨它有错误的返回类型,因为它是期待一个无效的方法。因此,增加对运行的重载的需要,而不是一个行动FUNC:

... the compiler complains that it has the wrong return type, because it is expecting a void method. So, add an overload for Run that takes a Func instead of Action:

public static IEnumerable<T> Run<T>(this IEnumerable<T> source, Func<T, T> action)
{
    return source.Select(action).ToList().AsEnumerable();
}

和现在的编译器抱怨的号召是以下方法之间的暧昧。 ..

And now the compiler complains that "The call is ambiguous between the following methods..."

所以我的问题是,如何才能Run方法引起歧义的超负荷动作时,它是不是有效的方法组?

So my question is, how can the Action overload of the Run method cause ambiguity when it is not valid for the method group?

推荐答案

这已经由Eric和Jon在答案的这个问题。长话短说 - 这是C#编译器是如何工作的;准确地说,与方法组转换处理决定什么样的委托,将被转换为使用重载决议,其中时,不采取帐户返回类型

This has already been explained by Eric and Jon in answers to this question. Long story short - this is how C# compiler works; precisely, when dealing with method group conversion deciding what delegate it will be converted to utilizes overload resolution, which does not take return types in account:

这里的原则是确定方法组可兑换需要使用重载的方法组中选择的方法和重载不考虑返回类型。

The principle here is that determining method group convertibility requires selecting a method from a method group using overload resolution, and overload resolution does not consider return types.

在您的例子编译器看到两个动作< T> Func键< T,T> 最佳匹配的为添加。这就增加了两种可能的选择,而且由于它需要一个 - 发出适当的错误

In your example compiler sees both Action<T> and Func<T, T> as best match for Add. This adds up to two possible choices, and since it requires one - appropriate error is issued.

这篇关于为什么不C#的Func键℃至重载工作; T,T&GT;和行动&LT; T&GT ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆