【发布时间】:2012-08-29 08:39:15
【问题描述】:
可能重复:
How do I use reflection to determine the nested type of an array?
我有一个 A 类,并试图在其中获取数组的基础类型。
Class A
{
A1[] obja1;
A2[] obja2;
string x;
int i;
}
如何将 obja1 的底层对象类型设为 A1,将 obja2 的底层对象类型设为 A2?这是我拥有的代码部分:
object AClass = myAssembly.CreateInstance("A");
PropertyInfo[] pinfos = AClass.GetType().GetProperties();
foreach(PropertyInfo pinfo in pinfos)
{
if(pinfo.PropertyType.IsArray)
{
//here get the the underlying property type so that I can do something as follows
var arr = myAssembly.CreateInstance(typeof(A1), 100);
//need to get if the array is array of A1 or A2 but do not want to hardcode
}
}
Thanks for the help..
【问题讨论】:
-
通过我的阅读,问题是询问如何创建数组类型的实例,而不是元素类型,因此它不一定是链接问题的副本。要创建数组,请使用
if (pinfo.PropertyType.IsArray) { var arr = Array.CreateInstance(pinfo.PropertyType.GetElementType, elementCount); ...其中 elementCount 是一个整数变量,用于保存所需的数组长度。 -
非常感谢..我太笨了,完全忘记了GetElementType
标签: c# system.reflection system.array