如何动态生成和填充多维数组 [英] How can I dynamically generate and populate a multi-dimensional array

查看:66
本文介绍了如何动态生成和填充多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究序列化器,遇到了带有多维数组的真实墙。如果我使用 Activator.CreateInstance(),它会创建一个一维数组,但它按以下方式使用时却无法正常工作:

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;

如果我改用 Array.CreateInstance()生成我的数组,它适用于一维和多维数组。但是,我对数组上的 SetValue()方法的所有调用(我用来动态设置值)都会产生一个异常,而它在单维数组上也能正常工作使用 Activator.CreateInstance()创建。我真的在努力寻找可行的解决方案,以允许我动态创建任意尺寸/大小的数组,然后使用值填充该数组。我希望有更多反思经验的人可以对此有所了解。

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.

尝试创建多重带有Activator的三维数组我得到一个例外:

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


找不到类型'System.Int32 [,]'的构造函数。

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

当我改用Array.CreateInstance()然后调用SetValue()时,我从SetValue()调用中得到以下异常:

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.

坦率地说,这对我来说毫无意义,因为该值是一个int值,而数组是一个int [,]。

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

我在我的项目中使用的是4.5框架我也用4.6重新创建了这个问题。

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

推荐答案

您可以调用 Array.CreateInstance 具有实际的 ElementType ,在这种情况下为 int

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);

然后可以用 SetValue 填充数组没有任何例外。例如,

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 ] ]

这篇关于如何动态生成和填充多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆