我如何使用反射创建一个C#阵列和专用型的信息? [英] How do I create a C# array using Reflection and only type info?

查看:130
本文介绍了我如何使用反射创建一个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.

推荐答案

我想补充到乔恩的答案。究其原因尝试失败,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屋!

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