如何使用反射获取对象的属性? [英] How do I get the properties of an object using reflection?

查看:39
本文介绍了如何使用反射获取对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以做到这一点

I know I can do this

foreach (PropertyInfo property in myobject.GetType().GetProperties())
{
    if (property.DeclaringType.ToString() == myobject.GetType().ToString())
    {
         // only have my object properties here
         // and not parent of my object properties
    }
}

但是我怎样才能只是获得 myobject 的属性而不是父对象的属性?即不必执行额外的 if 语句.

But how can I just get the properties of myobject and not those of the parent as well? ie not have to do that extra if statement.

编辑答案,(感谢@Greg Beech)这有效:-

edited for answer, (Thanks @Greg Beech) This worked:-

foreach (PropertyInfo property in 
             myobject.GetType().GetProperties
                 (BindingFlags.Public | 
                  BindingFlags.DeclaredOnly | 
                  BindingFlags.Instance))
{
    // only properties of my object not parent of myobject
}

我也找到了这个链接http://msdn.microsoft.com/en-us/library/4ek9c21e.aspx

推荐答案

查看 BindingFlags.DeclaredOnly 并将其传递给 GetProperties(您可能希望将其合并至少使用 BindingFlags.PublicBindingFlags.Instance).

Check out BindingFlags.DeclaredOnly and pass that to GetProperties (you'll probably want to combine it with BindingFlags.Public and BindingFlags.Instance at least).

这篇关于如何使用反射获取对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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