有没有一种方法可以不使用await foreach来返回IAsyncEnumerable

时间:2019-11-14 18:03:08

标签: c#

在MethodB的返回签名是IAsyncEnumerable的情况下,并且在MethodA内部调用它的情况下,可以返回IAsyncEnumerable,而无需如下迭代迭代MethodB的返回值:

IAsyncEnumerable<T> MethodB() => do stuff;

IAsyncEnumerable<T> MethodA() => return MethodB(); <- this gives a compiler error: must use yield return;

根据错误消息,我认为执行此操作的唯一方法如下:

async IAsyncEnumerable<T> MethodA() => await foreach(var t in MethodB())yield return t;

1 个答案:

答案 0 :(得分:5)

您正在为MethodA使用错误的语法-您正在使用表达式主体成员 return语句。您可以使用身体健全的成员:

IAsyncEnumerable<T> MethodB() => null;

IAsyncEnumerable<T> MethodA()
{
    return MethodB();
}

或仅删除return语句:

IAsyncEnumerable<T> MethodB() => null;

IAsyncEnumerable<T> MethodA() => MethodB();

这并不是真正针对IAsyncEnumerable<T>的问题-仅仅是返回类型给您的错误消息比您通常会得到的混乱得多:

// Invalid expression term 'return'
int Method() => return 0;