dimanche 27 décembre 2015

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

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[,].





Aucun commentaire:

Enregistrer un commentaire