Ben*_*Ben 8 c# generics task async-await .net-core
Task我正在尝试为with as 类型参数创建一个扩展方法,IEnumerable<T>该方法将返回IAsyncEnumerable<T>. 我想要这个的原因是为了满足接口。我尝试过,但总是出现错误
我的问题:是否可以有一个像我的第一个示例一样的扩展方法,适用于 的类型参数的实现,而Task不必为扩展方法指定类型参数?
这是我创建的扩展方法:
public static class EnumerableExtensions
{
public static async IAsyncEnumerable<T> GetAsyncEnumerable<T, TEnumerable>(this Task<TEnumerable> task) where TEnumerable : IEnumerable<T>
{
foreach (var item in await task)
{
yield return item;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这样就编译成功了。它的问题是我无法在IEnumerable类似ICollection<T>或List<T>类似的实现上调用它:
var enumerable = Task.FromResult(new List<int>()).GetAsyncEnumerable();
Run Code Online (Sandbox Code Playgroud)
它会抛出这个错误:
The type arguments for method 'IAsyncEnumerable<T> Demo.EnumerableExtensions.GetAsyncEnumerable<T,TEnumerable>(this Task<TEnumerable>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Run Code Online (Sandbox Code Playgroud)
当我指定类型参数时,它会编译:var enumerable = Task.FromResult(new List<int>()).GetAsyncEnumerable<int, List<int>>();
我也尝试过这个变体,但这也不起作用:
public static class EnumerableExtensions
{
public static async IAsyncEnumerable<T> GetAsyncEnumerable<T>(this Task<IEnumerable<T>> task)
{
foreach (var item in await task)
{
yield return item;
}
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出这个错误:
The type arguments for method 'IAsyncEnumerable<T> Demo.EnumerableExtensions.GetAsyncEnumerable<T>(this Task<IEnumerable<T>>)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
Run Code Online (Sandbox Code Playgroud)