Array initialization with default constructor

前端 未结 6 1359
渐次进展
渐次进展 2020-11-30 09:15
public class Sample
{
     static int count = 0;
     public int abc;
     public Sample()
     {
        abc = ++Sample.count;
     }
}

I want to

6条回答
  •  抹茶落季
    2020-11-30 09:33

    Here is another one-liner that doesn't require any extension method:

    Sample[] array = Enumerable.Range(0, 100).Select(i => new Sample()).ToArray();
    

    Another nice option is Scott's suggestion to Jon's answer:

    public static T[] Populate(this T[] array) 
        where T : new()
    {
        for (int i = 0; i < array.Length; i++)
            array[i] = new T();
        return array;
    }
    

    So you can do:

    Sample[] array = new Sample[100].Populate();
    

提交回复
热议问题