c# - 有没有办法在不使用 await foreach 的情况下返回 IAsyncEnumerable

标签 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;

最佳答案

您只是对 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/

相关文章:

c# - Aspx 到 Razor 语法转换器?

c# - NUnit 中的 Assembly.GetEntryAssembly()

c# - 将数字四舍五入,使其可以被 5 整除

c# - Sonarqube 是否支持 Xamarin 的代码质量?

c# - ParseExact 字符串到 DateTime 失败

c# - 我怎样才能从队列中创建一个 IObservable,这样序列就不会在队列为空时结束?

c# - gRPC c# 中的全局异常处理

c# - 从 C# 运行 Python 函数

c# - 如何手动编译一个C#项目?

c# - 使用iTunes SDK播放音频文件