This question already has an answer here:
这个问题已经有了答案:
- How can I create an instance of an arbitrary Array type at runtime? 4 answers
- 如何在运行时创建任意数组类型的实例?4答案
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.
秘诀是什么?如果我能得到数组元素的类型,我可以让第二个工作,但我也没算出来。
2 个解决方案
#1
31
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:
只是想补充一下琼恩的回答。尝试1失败的原因是没有Int32[]的默认构造函数。你需要提供长度。如果你使用了重载,它会用到一系列的参数:
// attempt1
object y1 = Activator.CreateInstance(t, new object[] { 1 }); // Length 1
#2
48
You need Type.GetElementType()
to get the non-array type:
您需要type . getelementtype()来获取非数组类型:
object x = new Int32[7];
Type t = x.GetType();
object y = Array.CreateInstance(t.GetElementType(), 7);
Alternatively, if you can get the type of the element directly, use that:
或者,如果您可以直接获得元素的类型,可以使用以下方法:
Type t = typeof(int);
object y = Array.CreateInstance(t, 7);
Basically, Array.CreateInstance
needs the element type of the array to create, not the final array type.
基本上,数组。CreateInstance需要阵列的元素类型来创建,而不是最终的数组类型。
#1
31
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:
只是想补充一下琼恩的回答。尝试1失败的原因是没有Int32[]的默认构造函数。你需要提供长度。如果你使用了重载,它会用到一系列的参数:
// attempt1
object y1 = Activator.CreateInstance(t, new object[] { 1 }); // Length 1
#2
48
You need Type.GetElementType()
to get the non-array type:
您需要type . getelementtype()来获取非数组类型:
object x = new Int32[7];
Type t = x.GetType();
object y = Array.CreateInstance(t.GetElementType(), 7);
Alternatively, if you can get the type of the element directly, use that:
或者,如果您可以直接获得元素的类型,可以使用以下方法:
Type t = typeof(int);
object y = Array.CreateInstance(t, 7);
Basically, Array.CreateInstance
needs the element type of the array to create, not the final array type.
基本上,数组。CreateInstance需要阵列的元素类型来创建,而不是最终的数组类型。