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

cub*_*nyc 1 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;
Run Code Online (Sandbox Code Playgroud)

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

async IAsyncEnumerable<T> MethodA() => await foreach(var t in MethodB())yield return t;
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

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

IAsyncEnumerable<T> MethodB() => null;

IAsyncEnumerable<T> MethodA()
{
    return MethodB();
}
Run Code Online (Sandbox Code Playgroud)

或只是删除以下return语句:

IAsyncEnumerable<T> MethodB() => null;

IAsyncEnumerable<T> MethodA() => MethodB();
Run Code Online (Sandbox Code Playgroud)

这并不是真正特定的IAsyncEnumerable<T>-只是返回类型给您的错误消息比通常的错误提示略多:

IAsyncEnumerable<T> MethodB() => null;

IAsyncEnumerable<T> MethodA() => MethodB();
Run Code Online (Sandbox Code Playgroud)