問(wèn)題描述
在我不斷追求減少吸吮的過(guò)程中,我試圖理解yield"語(yǔ)句,但我一直遇到同樣的錯(cuò)誤.
In my everlasting quest to suck less I'm trying to understand the "yield" statement, but I keep encountering the same error.
[someMethod] 的主體不能是迭代器塊,因?yàn)?System.Collections.Generic.List<AClass>' 不是迭代器接口類(lèi)型.
The body of [someMethod] cannot be an iterator block because 'System.Collections.Generic.List< AClass>' is not an iterator interface type.
這是我卡住的代碼:
foreach (XElement header in headersXml.Root.Elements()){
yield return (ParseHeader(header));
}
我做錯(cuò)了什么?我不能在迭代器中使用 yield 嗎?那有什么意義呢?在此示例中,它表示 List<ProductMixHeader>
不是迭代器接口類(lèi)型.ProductMixHeader
是一個(gè)自定義類(lèi),但我想 List
是一個(gè)迭代器接口類(lèi)型,不是嗎?
What am I doing wrong? Can't I use yield in an iterator? Then what's the point?
In this example it said that List<ProductMixHeader>
is not an iterator interface type.
ProductMixHeader
is a custom class, but I imagine List
is an iterator interface type, no?
--編輯--
感謝所有快速回答.
我知道這個(gè)問(wèn)題并不是那么新鮮,并且不斷出現(xiàn)相同的資源.
原來(lái)我在想我可以返回 List<AClass>
作為返回類(lèi)型,但由于 List<T>
不是惰性的,它不能.將我的返回類(lèi)型更改為 IEnumerable<T>
解決了問(wèn)題:D
--Edit--
Thanks for all the quick answers.
I know this question isn't all that new and the same resources keep popping up.
It turned out I was thinking I could return List<AClass>
as a return type, but since List<T>
isn't lazy, it cannot. Changing my return type to IEnumerable<T>
solved the problem :D
一個(gè)有點(diǎn)相關(guān)的問(wèn)題(不值得打開(kāi)一個(gè)新線程):如果我確定 99% 的情況我要去,是否值得將 IEnumerable<T>
作為返回類(lèi)型去 .ToList() 反正?性能影響是什么?
A somewhat related question (not worth opening a new thread): is it worth giving IEnumerable<T>
as a return type if I'm sure that 99% of the cases I'm going to go .ToList() anyway? What will the performance implications be?
推薦答案
使用yield return的方法必須聲明為返回以下兩個(gè)接口之一:
A method using yield return must be declared as returning one of the following two interfaces:
IEnumerable<SomethingAppropriate>
IEnumerator<SomethingApropriate>
(感謝 喬恩 和 Marc 用于指出 IEnumerator)
(thanks Jon and Marc for pointing out IEnumerator)
例子:
public IEnumerable<AClass> YourMethod()
{
foreach (XElement header in headersXml.Root.Elements())
{
yield return (ParseHeader(header));
}
}
yield 是一個(gè)懶惰的數(shù)據(jù)生產(chǎn)者,僅在檢索到第一個(gè)項(xiàng)目后才生成另一個(gè)項(xiàng)目,而返回列表將一次性返回所有內(nèi)容.
yield is a lazy producer of data, only producing another item after the first has been retrieved, whereas returning a list will return everything in one go.
所以有區(qū)別,需要正確聲明方法.
So there is a difference, and you need to declare the method correctly.
有關(guān)更多信息,請(qǐng)閱讀 Jon 的答案,其中包含一些非常有用的鏈接.
For more information, read Jon's answer here, which contains some very useful links.
這篇關(guān)于一些有助于理解“產(chǎn)量".的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!