Creating a list filled with new instances of an object

前端 未结 4 477
情深已故
情深已故 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:22

    Not sure what is wrong with a for loop in this case. At the very least, we can presize the capacity of the list. That might not be important for 100 objects, but the size is arbitrary.

    public class MyClass
    {
        static int Capacity = 100;
        static List<MyObj> MyObjs = new List<MyObj>(Capacity);
    
        static MyClass() {
           for( var i = 0; i < Capacity; i++ ) {
              MyObjs.Add(new MyObj());
           }
        }
    }
    
    0 讨论(0)
  • 2021-01-11 12:25

    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();
        }
    }
    
    0 讨论(0)
  • 2021-01-11 12:34

    Apparently, the answer is "no". Thanks, everyone!

    0 讨论(0)
  • 2021-01-11 12:39

    Edited to reflect that this method does not work.

    I was curious about your comment about Enumerable.Repeat, so I tried it.

    //do not use!
    List<object> myList = Enumerable.Repeat(new object(), 100).ToList();
    

    I confirmed that they do all share the same reference like the OP mentioned.

    0 讨论(0)
提交回复
热议问题