小编典典

正确使用“收益回报”

all

yield关键字是C# 中一直让我感到迷惑的关键字之一,而且我从来没有信心自己正确地使用它。

在以下两段代码中,哪个是首选,为什么?

版本 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;
        }
    }
}

版本 2: 返回列表

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

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

阅读 137

收藏
2022-02-28

共1个答案

小编典典

当我计算列表中的下一个项目(甚至是下一组项目)时,我倾向于使用 yield-return。

使用您的第 2 版,您必须在返回之前拥有完整的列表。通过使用yield-return,您实际上只需要在返回之前拥有下一个项目。

除其他外,这有助于将复杂计算的计算成本分散到更大的时间范围内。例如,如果列表连接到 GUI 并且用户从未转到最后一页,则您永远不会计算列表中的最终项目。

另一种优选收益回报的情况是 IEnumerable 表示无限集。考虑素数列表,或无限的随机数列表。您永远无法一次返回完整的
IEnumerable,因此您使用 yield-return 以增量方式返回列表。

在您的特定示例中,您拥有完整的产品列表,因此我将使用版本 2。

2022-02-28