Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
359 views
in Technique[技术] by (71.8m points)

c# retrieving type of array element using reflection

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;}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...