I have 3 different classes (1 parent and 2 children), and I have created a heterogeneous array:
Parent[] parentArray = new Parent[9];
I would like to populate this array with 3 Parent objects, 3 child1 objects, and 3 child2 objects, in that order.
I would like to know if there is a more elegant way to do it than just doing this:
parentArray[0] = new Parent();
parentArray[1] = new Parent();
parentArray[2] = new Parent();
parentArray[3] = new Child1();
parentArray[4] = new Child1();
....
parentArray[9] = new Child2();
Thanks!
Like this?
var parentArray = new Parent[]
{
new Parent(),
new Parent(),
new Parent(),
new Child1(),
...
};
Personal i just think you should use the object initializer. However for sheer boredom you can use Linq and a generic factory method.
// Given
public static IEnumerable<T> Factory<T>(int count) where T : Parent, new()
=> Enumerable.Range(0, count).Select(x => new T());
...
// Usage
var array = Factory<Parent>(3)
.Union(Factory<Child1>(3))
.Union(Factory<Child2>(3))
.ToArray();
In this situation, you want to perform a certain number of actions repeatedly. Loops are commonly used to do this. Because you're initializing an array, for
loops are a good fit, as they expose an integer that can be used to index the array. In your scenario, you can use three such loops.
Parent[] parentArray = new Parent[9];
for (int i = 0; i < 3; i++)
{
parentArray[i] = new Parent();
}
for (int i = 3; i < 6; i++)
{
parentArray[i] = new Child1();
}
for (int i = 6; i < 9; i++)
{
parentArray[i] = new Child2();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.