Creating a list filled with new instances of an object

前端 未结 4 478
情深已故
情深已故 2021-01-11 12:04

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?

<         


        
4条回答
  •  攒了一身酷
    2021-01-11 12:25

    This wouldn't be hard to implement as an iterator:

    IEnumerable CreateItems (int count) where T : new() {
        return CreateItems(count, () => new T());
    }
    
    IEnumerable CreateItems (int count, Func creator) {
        for (int i = 0; i < count; i++) {
            yield return creator();
        }
    }
    

提交回复
热议问题