如何根据以下代码使用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;}
}
答案 0 :(得分:4)
Array.CreateInstance
的第一个参数需要数组的元素类型。您传递了整个属性类型,正如您刚刚通过检查property.PropertyType.IsArray
找到的那样,数组类型(具体地,Bar[]
- 即Bar
元素数组)。
要获取数组类型的元素类型,请使用其GetElementType
方法:
var array = Array.CreateInstance(property.PropertyType.GetElementType(), 0);
我想你会在需要时用更高的数字替换传递给第二个参数的零,除非你实际上只想要空数组。