创建一个填充有对象新实例的列表 [英] Creating a list filled with new instances of an object
本文介绍了创建一个填充有对象新实例的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
用相同对象的任意数量的实例创建列表的最佳方法是什么?即有没有更紧凑或有效的方法来执行以下操作?
What's the best way to create a list with an arbitrary number of instances of the same object? i.e is there a more compact or efficient way to do the following?
static List<MyObj> MyObjs = Enumerable.Range(0, 100)
.Select(i => new MyObj())
.ToList();
(Enumerable.Repeat
将给我十个对同一对象的引用,所以我认为它不起作用.)
(Enumerable.Repeat
would give me ten references to the same object, so I don't think it would work.)
推荐答案
这并不难实现为迭代器:
This wouldn't be hard to implement as an iterator:
IEnumerable<T> CreateItems<T> (int count) where T : new() {
return CreateItems(count, () => new T());
}
IEnumerable<T> CreateItems<T> (int count, Func<T> creator) {
for (int i = 0; i < count; i++) {
yield return creator();
}
}
这篇关于创建一个填充有对象新实例的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文