![](/img/trans.png)
[英]How to return ActionResult along with async foreach and IAsyncEnumerable
[英]Is there a way to return an IAsyncEnumerable without using await foreach
在 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
使用了錯誤的語法 - 您正在使用表達式主體成員和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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.