【问题标题】:c# retrieving type of array element using reflectionc# 使用反射检索数组元素的类型
【发布时间】:2013-09-28 21:52:59
【问题描述】:

如何根据下面的代码使用反射实例化一个数组属性?

public class Foo
{
   public Foo()
   {
      foreach(var property in GetType().GetProperties())
      {
         if (property.PropertyType.IsArray)
         { 
            // the line below creates a 2D array of type Bar.  How to fix?
            var array = Array.CreateInstance(property.PropertyType, 0);
            property.SetValue(this, array, null);
         }
      }
   }
   public Bar[] Bars {get;set;}
}

public class Bar
{
    public string Name {get;set;}
}

【问题讨论】:

    标签: c# arrays reflection


    【解决方案1】:

    Array.CreateInstance 的第一个参数需要数组的元素类型。您传递了整个属性类型,正如您刚刚通过检查 property.PropertyType.IsArray 发现的那样,这是一个数组类型(具体来说,Bar[] - 即一个由 Bar 元素组成的数组)。

    要获取数组类型的元素类型,使用它的GetElementType方法:

    var array = Array.CreateInstance(property.PropertyType.GetElementType(), 0);
    

    我想你会在需要时将传递给第二个参数的零替换为更大的数字,除非你实际上只想要空数组。

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-17
      • 2015-07-25
      相关资源
      最近更新 更多