c#使用反射检索数组元素的类型 [英] c# retrieving type of array element using reflection

查看:116
本文介绍了c#使用反射检索数组元素的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

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

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).

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

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

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

我想你会在需要时用更大的数字替换传递给第二个参数的零,除非你真的只想要空数组.

这篇关于c#使用反射检索数组元素的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆