如何使用反射和仅类型信息创建 C# 数组? [英] How do I create a C# array using Reflection and only type info?
本文介绍了如何使用反射和仅类型信息创建 C# 数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我不知道如何进行这项工作:
I can't figure out how to make this work:
object x = new Int32[7];
Type t = x.GetType();
// now forget about x, and just use t from here.
// attempt1
object y1 = Activator.CreateInstance(t); // fails with exception
// attempt2
object y2 = Array.CreateInstance(t, 7); // creates an array of type Int32[][] ! wrong
秘诀是什么?如果我能得到数组元素的类型,我可以使第二个工作,但我也没有想出那个.
What's the secret sauce? I can make the second one work if I can get the type of the elements of the array, but I haven't figured that one out either.
推荐答案
只是为了补充 Jon 的答案.尝试 1 失败的原因是 Int32[]
没有默认构造函数.您需要提供一个长度.如果您使用带有参数数组的重载,它将起作用:
Just to add to Jon's answer. The reason attempt 1 fails is because there's no default constructor for Int32[]
. You need to supply a length. If you use the overload, which takes an array of arguments it will work:
// attempt1
object y1 = Activator.CreateInstance(t, new object[] { 1 }); // Length 1
这篇关于如何使用反射和仅类型信息创建 C# 数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文