在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;
答案 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;