在 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;
最佳答案
您只是对 MethodA
使用了错误的语法- 您使用的是表达式主体和 返回语句。您可以使用 block 体成员:
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;
关于c# - 有没有办法在不使用 await foreach 的情况下返回 IAsyncEnumerable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58863190/