为什么调用不明确?'Task.Run(Action)' 和 'Task.Run(Func<Task>)' [英] Why is the call ambiguous? &#39;Task.Run(Action)&#39; and &#39;Task.Run(Func&lt;Task&gt;)&#39;

查看:67
本文介绍了为什么调用不明确?'Task.Run(Action)' 和 'Task.Run(Func<Task>)'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

public void CacheData()
{
    Task.Run((Action)CacheExternalData);
    Task.Run(() => CacheExternalData());

    Task.Run(CacheExternalDataTask);

    Task.Run(CacheExternalData);
}

public Task CacheExternalDataTask()
{
    // Long running code
    return Task.FromResult("Data");
}

public void CacheExternalData()
{
    // Long running code
}

为什么 Task.Run(CacheExternalData) 模棱两可?而Task.Run(CacheExternalDataTask)不是吗?

当使用 CacheExternalData 调用 Task.Run 时,我认为编译器很清楚该方法返回一个 Task 并且它应该解析为 Action?

When calling Task.Run with CacheExternalData I would have thought it was clear to the compiler that the method does not return a Task and it should resolve to an Action?

推荐答案

应该很清楚,但是语言规范从未说过不匹配的返回类型会在重载解析期间产生任何影响.正因为如此,没有规则说更喜欢 Action 而不是 Func.如果选择 Action,当然,它会起作用.如果 Func 会被选中,那么当然,你会得到一个错误.但要选择两者之一,重载解析必须成功,而且它没有考虑到这一点.

It should be clear, but the language specification never said that mismatched return types would have any effect during overload resolution. Because of that, there was no rule that said to prefer Action over Func<Task>. If Action would be picked, sure, it would work. If Func<Task> would be picked, then sure, you'd get an error. But to pick either, overload resolution has to succeed, and it isn't taking this into account.

这应该是固定的在 C# 7.3 中具有新的重载解析.

这篇关于为什么调用不明确?'Task.Run(Action)' 和 'Task.Run(Func<Task>)'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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