Creating a list filled with new instances of an object

前端 未结 4 496
情深已故
情深已故 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: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 myList = Enumerable.Repeat(new object(), 100).ToList();
    
    
    

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

    提交回复
    热议问题