我想知道是否有一种方法可以编写一个函数来“通过”一个 IAsyncEnumerable ......也就是说,该函数将调用另一个 IAsyncEnumerable 函数并产生所有结果而无需编写 aforeach
来做到这一点?
我发现自己经常写这个代码模式。下面是一个例子:
async IAsyncEnumerable<string> MyStringEnumerator();
async IAsyncEnumerable<string> MyFunction()
{
// ...do some code...
// Return all elements of the whole stream from the enumerator
await foreach(var s in MyStringEnumerator())
{
yield return s;
}
}
Run Code Online (Sandbox Code Playgroud)
无论出于何种原因(由于分层设计),我的函数MyFunction
都想调用,MyStringEnumerator
但随后无需干预即可生成所有内容。我必须继续编写这些foreach
循环才能做到这一点。如果是,IEnumerable
我会返回IEnumerable
. 如果是 C++,我可以写一个宏来做到这一点。
什么是最佳实践?