开发者

How can i create array of my class with default constructor?

For example

MYCLASS[] myclass = new MYCLASS[10];

Now myclass array is all null array but i want to have default constructed Array .I know that i can write loops for set default constructed but i am looking for more easy and s开发者_如何学编程imple way.


If you don't want to write out the loop you could use Enumerable.Range instead:

MyClass[] a = Enumerable.Range(0, 10)
                        .Select(x => new MyClass())
                        .ToArray();

Note: it is considerably slower than the method you mentioned using a loop, written here for clarity:

MyClass[] a = new MyClass[10];
for (int i = 0; i < a.Length; ++i)
{
    a[i] = new MyClass();
}


var a = Enumerable.Repeat(new MYCLASS(), 10).ToArray();


There isn't an easier way. If you just don't like loops, you could use

MyClass[] array = new[] { new MyClass(), new MyClass(), new MyClass(), new MyClass() };

which would give you an array with 4 elements of type MyClass, constructed with the default constructor.

Otherwise, you just have the option to use a loop.

If you don't want to write that loop every time you want to construct your array, you could create a helper-method, for example as an extension method:

 static class Extension
 {
    public static void ConstructArray<T>(this T[] objArray) where T : new()
    {
        for (int i = 0; i < objArray.Length; i++)
            objArray[i] = new T();
    }
}

And then use it like this:

MyClass[] array = new MyClass[10];
array.ConstructArray();


There isn't really a better way. You could do something like:

public static T[] CreateArray<T>(int len) where T : class, new() {
    T[] arr = new T[len];
    for(int i = 0 ; i <arr.Length ; i++) { arr[i] = new T(); }
    return arr;
}

then at least you only need:

Foo[] data = CreateArray<Foo>(150);

This approach should at least avoid any reallocations, and can use the JIT array/length optimisation. The : class is to avoid use with value-types, as with value-types already initialize in this way; just new MyValueType[200] would be better.


You can use LINQ.

var a = (from x in Enumerable.Range(10) select new MyClass()).ToArray();


If we want to do all job in only one line code so this is best

MYCLASS[] myclass = (new MYCLASS[10]).Select(x => new MYCLASS()).ToArray();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜