一些帮助理解和QUOT;产量" [英] Some help understanding "yield"

查看:195
本文介绍了一些帮助理解和QUOT;产量"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我永恒的追求,少犯几次我一直撞到了收益的语句。

我试图总结我的头周围现在几次,但我难倒具有相同的错误每次。

In my everlasting quest to suck less I keep bumping into the "yield" statement.
I have tried to wrap my head around it a few times now, but I'm stumped every time with the same error.

它去有点像这样:

的[的someMethod]身体不能是迭代器块,因为
  System.Collections.Generic.List< ACLASS>'不是一个迭代器接口类型。

The body of [someMethod] cannot be an iterator block because 'System.Collections.Generic.List< AClass>' is not an iterator interface type.

这是code,我最后卡住了:

This is the code where I last got stuck:

        foreach (XElement header in headersXml.Root.Elements()){
            yield return (ParseHeader(header));                
        }

我是什么做错了吗?我不能用在一个迭代的收益呢?那么什么意义呢?
在这种情况下例如,它说,名单&LT; ProductMixHeader>不是一个迭代器接口类型。
ProductMixHeader是一个自定义类,但我想列表是一个迭代器接口类型,不?

What am I doing wrong? Can't I use the yield in an iterator? Then what's the point? In the case 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, not?

- 编辑 -
感谢所有的快速解答。答案给一个答案。
我知道这个问题是不是所有的新的和相同的resouces不断弹出。
原来,我想我可以回到列表作为返回类型,但脱离当然,因为列表不懒,也不能使用。改变我的返回类型IEnumerable的解决了这个问题:D

--Edit-- Thanks for all the quick answers. Answer given to first answer. I know this question isn't all that new and the same resouces keep popping up. It turned out I was thinking I could return List as a return type, but off course because List isn't lazy, it cannot be used. Changing my return type to IEnumerable solved the problem :D

现在有点相关的问题(不值得打开一个新的线程):这是值得给予了IEnumerable作为返回类型,如果我敢肯定,我要去.ToList()反正99%的情况?什么会为我做的表现吗?

Now a somewhat related question (not worth opening a new thread): is it worth giving IENumerable as a return type if I'm sure that 99% of the cases I'm going to go .ToList() anyway? What will performance do for me there?

推荐答案

使用方法的收益回报率的必须声明为返回以下两个接口之一:

A method using yield return must be declared as returning one of the following two interfaces:

IEnumerable<SomethingAppropriate>
IEnumerator<SomethingApropriate>

(感谢乔恩并的马克获取指出的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 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.

所以是有区别的,你需要正确地申报方法。

So there is a difference, and you need to declare the method correctly.

有关更多信息,请阅读乔恩的回答这里,其中包含了一些非常有用的链接

For more information, read Jon's answer here, which contains some very useful links.

这篇关于一些帮助理解和QUOT;产量&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆