小编Ben*_*Ben的帖子

如何使用通用类型参数(接口)实现任务的通用扩展方法

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 …

c# generics task async-await .net-core

8
推荐指数
0
解决办法
273
查看次数

标签 统计

.net-core ×1

async-await ×1

c# ×1

generics ×1

task ×1