C# async SelectMany()扩展方法无法推断类型参数
我正努力用我从中采用的异步扩展方法来处理类型推断C# async SelectMany()扩展方法无法推断类型参数,c#,.net,linq,asynchronous,C#,.net,Linq,Asynchronous,我正努力用我从中采用的异步扩展方法来处理类型推断 parents的类型为IList ReturnsChildrenAsync()返回一个任务 但我得到了以下错误: 无法从用法推断方法“EnumerableExtensions.SelectManyAsync(IEnumerable,Func)”的类型参数。尝试显式指定类型参数 似乎无法推断T1。为什么这不能从任务?中派生出来,因为任务!=Task?不是IList实现IEnumerable吗?你应该等待ReturnsChildrenAsync在la
parents
的类型为IList
ReturnsChildrenAsync()
返回一个任务
但我得到了以下错误:
无法从用法推断方法“EnumerableExtensions.SelectManyAsync(IEnumerable,Func)”的类型参数。尝试显式指定类型参数
似乎无法推断
T1
。为什么这不能从任务
?中派生出来,因为任务
!=Task
?不是IList
实现IEnumerable
吗?你应该等待ReturnsChildrenAsync
在lambda表达式中。好吧,找到Eric Lippert与老虎和长颈鹿关于协方差和逆变的答案之一。我认为问题是Task
是在.Net 4中添加之前编写的,它根本不在框架中。你可以打开一个bug。
public static class EnumerableExtensions
{
public static async Task<IEnumerable<T1>> SelectAsync<T, T1>(
this IEnumerable<T> enumeration,
Func<T, Task<T1>> func)
{
return await Task.WhenAll(enumeration.Select(func));
}
public static async Task<IEnumerable<T1>> SelectManyAsync<T, T1>(
this IEnumerable<T> enumeration,
Func<T, Task<IEnumerable<T1>>> func)
{
return (await enumeration.SelectAsync(func)).SelectMany(x => x);
}
}
var allChildren = await parents.SelectManyAsync(parent => ReturnsChildrenAsync(parent));