c#使用反射检索数组元素的类型

时间:2013-09-28 21:53:00

标签: c# arrays reflection

如何根据以下代码使用Reflection实例化数组属性?

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;}
}

1 个答案:

答案 0 :(得分:4)

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

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

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

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