为什么 Task.FromResult 需要显式转换?

Kzr*_*tof 6 c#

我有以下程序:

async Task Main()
{
    IList<int> myList = await TestAsync();
}

public Task<IList<int>> TestAsync()
{
    return Task.FromResult(new List<int>());
}
Run Code Online (Sandbox Code Playgroud)

编译器抱怨它无法在方法中将Task<List>a转换为 a :Task<IList>TestAsync

CS0029 无法将类型隐式转换 System.Threading.Tasks.Task<System.Collections.Generic.List<int>>System.Threading.Tasks.Task<System.Collections.Generic.IList<int>>

为什么它不知道我的方法返回 IList 的任务?

Jon*_*eet 10

为什么它不知道我的方法返回了一个 Task IList<int>

因为它没有。在这次通话中:

Task.FromResult(new List<int>());
Run Code Online (Sandbox Code Playgroud)

...类型推断使其等效于:

Task.FromResult<List<int>>(new List<int>());
Run Code Online (Sandbox Code Playgroud)

所以你的方法试图返回一个Task<List<int>>- 而这与Task<IList<int>>.

为了简化关于 的观点Task<>,让我们使用stringandobject代替,并完全去掉类型推断和异步。下面的代码不能编译,而且确实不应该:

Task<string> stringTask = Task.FromResult<string>("text");
Task<object> objectTask = stringTask; // Doesn't compile
Run Code Online (Sandbox Code Playgroud)

Task<T>不变的- 没有从Task<T1>to的转换,Task<T2>因为有从T1to的转换T2

不过,您不需要显式转换 - 您可以更早地使用隐式转换:

public Task<IList<int>> TestAsync()
{
    // It's important that this variable is explicitly typed as IList<int>
    IList<int> result = new List<int>();
    return Task.FromResult(result);
}
Run Code Online (Sandbox Code Playgroud)

这对变量使用从List<int>到的隐式转换,然后使用类型推断进行调用。IList<int>resultTask.FromResult<IList<int>>

另一种方法是保持方法原样,除非您为 指定类型参数Task.FromResult

public Task<IList<int>> TestAsync()
{
    return Task.FromResult<IList<int>>(new List<int>());
}
Run Code Online (Sandbox Code Playgroud)