簡體   English   中英

有沒有辦法在不使用 await foreach 的情況下返回 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM