正确使用'收益率'

こ雲淡風輕ζ 提交于 2020-10-16 05:27:17

问题:

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. yield关键字是C#中那些继续使我神秘化的关键字之一,而且我从未确信我正确使用它。

Of the following two pieces of code, which is the preferred and why? 以下两段代码中,哪个是首选,为什么?

Version 1: Using yield return 版本1:使用收益率返回

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 版本2:返回列表

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

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

解决方案:

参考一: https://stackoom.com/question/1ifK/正确使用-收益率
参考二: https://oldbug.net/q/1ifK/Proper-use-of-yield-return
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!