How do I get the properties of an object using ref

2019-07-19 01:19发布

问题:

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

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.

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
}

I also found this link http://msdn.microsoft.com/en-us/library/4ek9c21e.aspx

回答1:

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



标签: c# reflection