正确使用迭代器块 [英] Correct usage of iterator blocks
问题描述
我之前正在重构一些代码,我遇到了一个迭代器块的实现,我不太确定。在客户端为某些数据调用extrernal API的系统的集成层中,我有一组转换器,它们从API返回的数据并将其转换为逻辑层中使用的业务实体的集合。常见的翻译类将如下所示:
I was refactoring some code earlier and I came across an implementation of an iterator block I wasn't too sure about. In an integration layer of a system where the client is calling an extrernal API for some data I have a set of translators that take the data returned from the API and translate it into collections of business entities used in the logic layer. A common translator class will look like this:
// translate a collection of entities coming back from an extrernal source into business entities
public static IEnumerable<MyBusinessEnt> Translate(IEnumerable<My3rdPartyEnt> ents) {
// for each 3rd party ent, create business ent and return collection
return from ent in ents
select new MyBusinessEnt {
Id = ent.Id,
Code = ent.Code
};
}
今天我遇到了以下代码。同样,它是一个翻译类,它的目的是将参数中的集合转换为方法返回类型。但是,这次它是一个迭代器块:
Today I came across the following code. Again, it's a translator class, it's purpose is to translate the collection in the parameter into the method return type. However, this time it's an iterator block:
// same implementation of a translator but as an iterator block
public static IEnumerable<MyBusinessEnt> Translate(IEnumerable<My3rdPartyEnt> ents) {
foreach(var ent in ents)
{
yield return new MyBusinessEnt {
Id = ent.Id,
Code = ent.Code
};
}
}
我的问题是:这是有效的使用迭代器块?我看不出以这种方式创建翻译类的好处。这会导致一些意想不到的行为吗?
推荐答案
你的两个样本几乎完全相同。查询版本将被重写为对Select的调用,而Select的编写方式与第二个示例完全相同;它迭代源集合中的每个元素,并返回一个转换后的元素。
Your two samples do pretty much exactly the same thing. The query version will be rewritten into a call to Select, and Select is written exactly like your second example; it iterates over each element in the source collection and yield-returns a transformed element.
这是对迭代器块的完全有效的使用,当然它不再是必需来编写这样的迭代器块,因为你可以使用选择
。
This is a perfectly valid use of an iterator block, though of course it is no longer necessary to write your own iterator blocks like this because you can just use Select
.
这篇关于正确使用迭代器块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!