Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

c# - Array initialization with default constructor

public class Sample
{
     static int count = 0;
     public int abc;
     public Sample()
     {
        abc = ++Sample.count;
     }
}

I want to create an array of above class, and want each element in the array to be initialized by invoking the default constructor, so that each element can have different abc.So I did this:

Sample[] samples = new Sample[100];

But this doesn't do what I think it should do. It seems this way the default constructor is not getting called. How to invoke default constructor when creating an array?

I also would like to know what does the above statement do?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can't, basically. When you create an array, it's always initially populated with the default value for the type - which for a class is always a null reference. For int it's 0, for bool it's false, etc.

(If you use an array initializer, that will create the "empty" array and then populate it with the values you've specified, of course.)

There are various ways of populating the array by calling the constructor - I would probably just use a foreach loop myself. Using LINQ with Enumerable.Range/Repeat feels a little forced.

Of course, you could always write your own population method, even as an extension method:

public static T[] Populate<T>(this T[] array, Func<T> provider)
{
    for (int i = 0; i < array.Length; i++)
    {
        array[i] = provider();
    }
    return array;
}

Then you could use:

Sample[] samples = new Sample[100].Populate(() => new Sample());

What I like about this solution:

  • It's still a single expression, which can be useful in various scenarios
  • It doesn't introduce concepts you don't actually want (like repeating a single value or creating a range)

Of course you could add more options:

  • An overload which takes a Func<int, T> instead of a Func<T>, passing the index to the provider
  • A non-extension method which creates the array and populates it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...