How to use reflection to get only the public properties of an object instance?

I reflect on an object and I want only public properties of an instance, I do not want public static properties. The problem is that it GetProperties()returns both static and public. Anyone have an idea how best to approach this issue?

private IOrderedEnumerable<PropertyInfo> GetSortedPropInfos()
{
    return dataExtractor.GetType().GetProperties().OrderBy(
            p => p.Name );
}

Notice, I am sorting the list, since it GetProperties()does not indicate any type of ordering, and ordering is important to me.

0
source share
4 answers
private IOrderedEnumerable<PropertyInfo> GetSortedPropInfos()
{
    return dataExtractor.GetType()
                        .GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .OrderBy( p => p.Name );
}
+1
source

Use another GetProperties overload , which allows you to specify anchor flags, such as BindingFlags.Instance.

return dataExtractor.GetType().GetProperties(
        BindingFlags.Instance | BindingFlags.Public).OrderBy(
        p => p.Name );
+1
source

Yes, you need to set the anchor flags in the constructor. Snap flags define flags that control the snap, and the way in which elements and types are searched by reflection. Take a look at the following information:

Enumeration of binding flags: http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx

0
source

Just indicating an addition to other answers - also use BindingFlags.DeclaredOnlyif you don't want inherited properties.

0
source

All Articles