含义与Action和Func参数 [英] Ambiguity with Action and Func parameter
问题描述
如何可能这个代码
TaskManager.RunSynchronously<MyObject>(fileMananager.BackupItems, package);
导致编译错误
The call is ambiguous between the following methods or properties:
'TaskManager.RunSynchronously<MyObject>(System.Action<MyObject>, MyObject)' and
'TaskManager.RunSynchronously<MyObject>(System.Func<MyObject, bool>, MyObject)'
public void BackupItems(MyObject package)
和ambiguous方法是
and "ambiguous" methods are
static class TaskManager
{
public static void RunSynchronously<TInput>(Action<TInput> task, TInput param)
{
Task.Factory.StartNew(() => task(param));
}
public static bool RunSynchronously<TInput>(Func<TInput, bool> task, TInput param)
{
return Task.Factory.StartNew(() => task(param)).Result;
}
}
在我看来,这些方法。我在这里缺少什么?
It seems to me that there is an ample difference between these methods. What am I missing here?
编辑:
除了接受的答案刚刚遇到一个类似问题的解决方案。以下是链接。
Besides the accepted answer I just came across a solution in a similar question. Here is the link.
推荐答案
原因是方法的返回类型不是其签名的一部分。因此,在解决正确的重载时,编译器仅查看方法的参数。
The reason is that the return type of a method is not part of its signature. Thus, while resolving the correct overload, the compiler only looks at the parameter of the method.
最简单的解决方案是简单地不使用隐式方法组转换。所有以下编译:
The easiest solution is to simply not use the implicit method group conversion. All of the following compile:
TaskManager.RunSynchronously<MyObject>(
x => fileMananager.BackupItems(x), package);
TaskManager.RunSynchronously<MyObject>(
(Action<MyObject>)fileMananager.BackupItems, package);
TaskManager.RunSynchronously<MyObject>(
new Action<MyObject>(fileMananager.BackupItems), package);
第一个是最优雅的,但它也是唯一一个 - 轻微的 - 运行时性能影响,因为额外的重定向。但是,这种影响是如此之小,您实际上不应该在乎。
The first one is the most elegant of them, but it also is the only one with a - slight - runtime performance impact, because of an additional redirection. However, this impact is so small that you actually shouldn't care.
这篇关于含义与Action和Func参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!