Ambiguity with Action and Func parameter

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-03 10:08:26

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.

I came across the same problem, the solution was:

var r = RunSynchronously<bool>(x =>
{
    return true;
}, true);

RunSynchronously<bool>(x =>
{
}, true);

Now, why the compiler cannot do that???

Another possible explanation for this nowadays is this:

The code was written for C# version 7.3 (used by default by MSBuild 16.x, corresponding to VS2019), but the build is attempted with an earlier version of C# (which is the default for MSBuild 15.x, corresponding to VS2017).

Earlier versions of C# throw this error, but the overload is resolved correctly in C# 7.3.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!