【发布时间】:2011-01-25 17:04:08
【问题描述】:
考虑一下这段混淆的代码。目的是通过匿名构造函数和yield return 动态创建一个新对象。目标是避免仅仅为了 return 它而维护本地集合。
public static List<DesktopComputer> BuildComputerAssets()
{
List<string> idTags = GetComputerIdTags();
foreach (var pcTag in idTags)
{
yield return new DesktopComputer() {AssetTag= pcTag
, Description = "PC " + pcTag
, AcquireDate = DateTime.Now
};
}
}
不幸的是,这段代码产生了异常:
错误 28 'Foo.BuildComputerAssets()' 的主体不能是迭代器块,因为 'System.Collections.Generic.List' 不是迭代器接口类型
问题
- 此错误消息是什么意思?
- 如何避免此错误并正确使用
yield return?
【问题讨论】: