【问题标题】:Get the type of an array object [duplicate]获取数组对象的类型[重复]
【发布时间】: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


【解决方案1】:

如果我的问题正确。您可以使用Get Element Type 获取元素类型并将其与所需的进行比较。

或者

只需使用typeof(A1[])typeof(A2[])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 2019-04-12
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    • 2019-06-28
    • 1970-01-01
    • 2021-07-20
    相关资源
    最近更新 更多