简体   繁体   中英

How can I dynamically generate and populate a multi-dimensional array

I'm working on a serializer and have run into a real wall with multi-dimensional arrays. If I use Activator.CreateInstance() it creates a one dimensional array just fine, but it fails to work when used as follows:

var indices = new[] { 2, 2 };
Type type = typeof(int[,]);
var result = Activator.CreateInstance(type, indices) as Array;

If I instead use Array.CreateInstance() to generate my array, it works for single and multi-dimensional arrays alike. However, all my calls to the SetValue() method on the array, which I use to dynamically set values, generates an exception, whereas it works fine on the single dimensional arrays I created using Activator.CreateInstance() . I'm really struggling to find a viable solution that allows me to dynamically create an array of any dimension/size and then populate the array with values. I'm hoping someone with more reflection experience can shed some light on this.

When trying to create a multi-dimensional array with Activator I get the exception:

Constructor on type 'System.Int32[,]' not found.

When I instead use Array.CreateInstance() and then call SetValue() I get the following exception from the SetValue() call:

Object cannot be stored in an array of this type.

Which frankly makes no sense to me since the value is an int and the array is an int[,].

I am using the 4.5 framework for my project though I recreated the problem with 4.6 as well.

You can call Array.CreateInstance with the actual ElementType which is int in this case.

var indices = new[] { 2, 3 };                
var arr = Array.CreateInstance(typeof(int), indices);

Then you can populate the array with SetValue without any exception. For example

var value = 1;
for (int i = 0; i < indices[0]; i++)
{
    for (int j = 0; j < indices[1]; j++)
    {
        arr.SetValue(value++, new[] { i, j });
    }
}

//arr = [ [ 1, 2, 3 ], [ 4, 5, 6 ] ]

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM