加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 使用包含其他对象数组的对象的反射读取属性

发布时间:2020-12-15 04:17:44 所属栏目:百科 来源:网络整理
导读:如何在c#中使用反射来读取包含数组类型元素的对象的属性.如果我有一个名为GetMyProperties的方法,我确定该对象是一个自定义类型,那么如何读取数组的属性和其中的值. IsCustomType是确定类型是否为自定义类型的方法. public void GetMyProperties(object obj)
如何在c#中使用反射来读取包含数组类型元素的对象的属性.如果我有一个名为GetMyProperties的方法,我确定该对象是一个自定义类型,那么如何读取数组的属性和其中的值. IsCustomType是确定类型是否为自定义类型的方法.
public void GetMyProperties(object obj) 
{ 
    foreach (PropertyInfo pinfo in obj.GetType().GetProperties()) 
    { 
        if (!Helper.IsCustomType(pinfo.PropertyType)) 
        { 
            string s = pinfo.GetValue(obj,null).ToString(); 
            propArray.Add(s); 
        } 
        else 
        { 
            object o = pinfo.GetValue(obj,null); 
            GetMyProperties(o); 
        } 
    } 
}

场景是,我有一个ArrayClass的对象,ArrayClass有两个属性:

-string Id
-DeptArray[] depts

DeptArray是另一个有2个属性的类:

-string code 
-string value

所以,这个方法得到一个ArrayClass的对象.我想从字典/列表项中读取所有属性,从顶到底,存储名称/值对.我能够为value,custom,enum类型做.我被卡住了数组的对象.不知道该怎么做

解决方法

尝试这段代码:
public static void GetMyProperties(object obj)
{
  foreach (PropertyInfo pinfo in obj.GetType().GetProperties())
  {
    var getMethod = pinfo.GetGetMethod();
    if (getMethod.ReturnType.IsArray)
    {
      var arrayObject = getMethod.Invoke(obj,null);
      foreach (object element in (Array) arrayObject)
      {
        foreach (PropertyInfo arrayObjPinfo in element.GetType().GetProperties())
        {
          Console.WriteLine(arrayObjPinfo.Name + ":" + arrayObjPinfo.GetGetMethod().Invoke(element,null).ToString());
        }
      }
    }
  }
}

我已经测试了这个代码,它通过反射来正确地解析了数组.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读