我正在开发一个序列化器,并且遇到了带有多维数组的真正的墙。如果我使用 Activator.CreateInstance() ,它会很好地创建一个一维数组,但在使用时无法工作,如下所示:
var indices = new[] { 2, 2 };
Type type = typeof(int[,]);
var result = Activator.CreateInstance(type, indices) as Array;
如果我使用 Array.CreateInstance() 来生成数组,它同样适用于单维和多维数组。但是,我对数组上的 SetValue()
方法(用于动态设置值)的所有调用都会生成异常,而它在我使用 Activator 创建的一维数组上运行良好.CreateInstance()。我真的很难找到一个可行的解决方案,它允许我动态创建任何维度/大小的数组,然后用值填充该数组。我希望有更多反射(reflection)
经验的人能够对此有所启发。
当尝试使用 Activator 创建多维数组时,出现异常:
Constructor on type 'System.Int32[,]' not found.
当我使用 Array.CreateInstance() 然后调用 SetValue() 时,我从 SetValue() 调用中得到以下异常:
Object cannot be stored in an array of this type.
坦率地说,这对我来说毫无意义,因为该值是一个 int 而数组是一个 int[,]。
我的项目使用的是 4.5 框架,尽管我也使用 4.6 重新创建了该问题。
最佳答案
您可以使用实际的 ElementType
调用 Array.CreateInstance
,在本例中为 int
。
var indices = new[] { 2, 3 };
var arr = Array.CreateInstance(typeof(int), indices);
然后您可以使用 SetValue
填充数组,没有任何异常。例如
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 ] ]
关于c# - 如何动态生成和填充多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487285/