正确使用“收益率回报” [英] Proper use of 'yield return'

查看:146
本文介绍了正确使用“收益率回报”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

借助产生关键字是其中之一的关键字在继续迷惑我的C#,那我正确地使用它,我从来没有自信。

code,这是preferred为什么?

以下两件

版本1:是收益率的回报。

 公共静态的IEnumerable<产品与GT; GetAllProducts()
{
    使用(AdventureWorksEntities DB =新AdventureWorksEntities())
    {
        VAR产品从产品中db.Product =
                       选择产品;        的foreach(在产品产品产品)
        {
            产生收益的产品;
        }
    }
}

版本2:返回列表

 公共静态的IEnumerable<产品与GT; GetAllProducts()
{
    使用(AdventureWorksEntities DB =新AdventureWorksEntities())
    {
        VAR产品从产品中db.Product =
                       选择产品;        返回products.ToList<产品及GT;();
    }
}


解决方案

我倾向于使用收益回报,当我计算列表中的下一个项目(甚至未来项目组)。

使用版本2,您必须在返回前有完整的列表。
通过使用收益回报,你真的只需要在返回前有下一个项目。

在其他方面,这有助于US $ p $垫复杂的计算在一个较大的时间帧中的计算成本。例如,如果列表被挂接到一个GUI和用户从不给最后一页,则从未计算列表中的最后条目。

,其中产量回报是preferable是,如果IEnumerable的再presents一组无限另一种情况。考虑质数的列表,或随机数的无限名单。你永远无法返回完整的IEnumerable一次,让你用收益回报逐步返回列表中。

在你的特殊的例子,你的产品的完整列表,所以我会用第2版。

The yield keyword is one of those keywords in C# that continues to mystify me, and I've never been confident that I'm using it correctly.

Of the following two pieces of code, which is the preferred and why?

Version 1: Using yield return

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        foreach (Product product in products)
        {
            yield return product;
        }
    }
}

Version 2: Return the list

public static IEnumerable<Product> GetAllProducts()
{
    using (AdventureWorksEntities db = new AdventureWorksEntities())
    {
        var products = from product in db.Product
                       select product;

        return products.ToList<Product>();
    }
}

解决方案

I tend to use yield-return when I calculate the next item in the list (or even the next group of items).

Using your Version 2, you must have the complete list before returning. By using yield-return, you really only need to have the next item before returning.

Among other things, this helps spread the computational cost of complex calculations over a larger time-frame. For example, if the list is hooked up to a GUI and the user never goes to the last page, you never calculate the final items in the list.

Another case where yield-return is preferable is if the IEnumerable represents an infinite set. Consider the list of Prime Numbers, or an infinite list of random numbers. You can never return the full IEnumerable at once, so you use yield-return to return the list incrementally.

In your particular example, you have the full list of products, so I'd use Version 2.

这篇关于正确使用“收益率回报”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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