c# retrieving type of array element using reflecti

2019-09-20 16:34发布

How do I instantiate an array property using Reflection based on the code below?

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条回答
戒情不戒烟
2楼-- · 2019-09-20 17:17

The first parameter of Array.CreateInstance expects the element type of the array. You pass the entire property type, which is, as you have just found out by checking property.PropertyType.IsArray, an array type (specifically, Bar[] - i.e. an array of Bar elements).

To get the element type of an array type, use its GetElementType method:

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

I suppose you will replace the zero passed to the second argument with a higher number when required, unless you actually want only empty arrays.

查看更多
登录 后发表回答