-2

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

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

1 回答 1

4

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

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

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

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

于 2013-09-28T21:57:01.680 回答