在如何只能暴露IList<>的一个片段问题中,其中一个答案有以下代码片段:
IEnumerable<object> FilteredList()
{
foreach(object item in FullList)
{
if(IsItemInPartialList(item))
yield return item;
}
}
yield关键字在这里做什么?我在一些地方看到过它,还有一个问题,但我还没搞清楚它到底是干什么的。我习惯于从一个线程屈服于另一个线程的意义上考虑屈服,但这在这里似乎无关紧要。
下面是理解这个概念的简单方法:
其基本思想是,如果您想要一个可以使用“foreach”的集合,但是由于某些原因将项收集到集合中成本很高(例如从数据库中查询它们),并且通常不需要整个集合,那么您可以创建一个函数,每次构建一个项集合并将其返回给消费者(然后消费者可以提前终止收集工作)。
Think of it this way: You go to the meat counter and want to buy a pound of sliced ham. The butcher takes a 10-pound ham to the back, puts it on the slicer machine, slices the whole thing, then brings the pile of slices back to you and measures out a pound of it. (OLD way).
With yield, the butcher brings the slicer machine to the counter, and starts slicing and "yielding" each slice onto the scale until it measures 1-pound, then wraps it for you and you're done. The Old Way may be better for the butcher (lets him organize his machinery the way he likes), but the New Way is clearly more efficient in most cases for the consumer.