.jpg)
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>();
}
}

网友回答:
填充临时列表就像下载整个视频,而使用就像流式传输该视频。yield

网友回答:
当我计算列表中的下一个项目(甚至下一组项目)时,我倾向于使用收益率回报。
使用版本 2,您必须在返回之前拥有完整列表。
通过使用收益回报,您实际上只需要在返回之前拥有下一项。
除此之外,这有助于将复杂计算的计算成本分摊到更大的时间范围内。例如,如果列表挂接到 GUI,并且用户从不转到最后一页,则永远不会计算列表中的最终项目。
收益率回报更可取的另一种情况是,如果 IEnumerable 表示一个无限集合。考虑质数列表,或无限随机数列表。您永远无法一次返回完整的 IEnumerable,因此您可以使用 yield-return 以增量方式返回列表。
在您的特定示例中,您拥有完整的产品列表,因此我将使用版本 2。

网友回答:
作为理解何时应该使用的概念示例,假设该方法处理由以下方法返回/生成的项目:yieldConsumeLoop()ProduceList()
void ConsumeLoop() {
foreach (Consumable item in ProduceList()) // might have to wait here
item.Consume();
}
IEnumerable<Consumable> ProduceList() {
while (KeepProducing())
yield return ProduceExpensiveConsumable(); // expensive
}
Without , the call to might take a long time because you have to complete the list before returning:yieldProduceList()
//pseudo-assembly
Produce consumable[0] // expensive operation, e.g. disk I/O
Produce consumable[1] // waiting...
Produce consumable[2] // waiting...
Produce consumable[3] // completed the consumable list
Consume consumable[0] // start consuming
Consume consumable[1]
Consume consumable[2]
Consume consumable[3]
Using , it becomes rearranged, sort of interleaved:yield
//pseudo-assembly
Produce consumable[0]
Consume consumable[0] // immediately yield & Consume
Produce consumable[1] // ConsumeLoop iterates, requesting next item
Consume consumable[1] // consume next
Produce consumable[2]
Consume consumable[2] // consume next
Produce consumable[3]
Consume consumable[3] // consume next
最后,正如之前许多人已经建议的那样,您应该使用版本 2,因为无论如何您已经拥有完整的列表。
模板简介:该模板名称为【在c#如何正确使用收益回报 ‘yield return’】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【C#】栏目查找您需要的精美模板。