简体   繁体   中英

How to use reflection to get just the object instance's public properties?

I'm reflecting on an object and only want the public properties of an instance, I don't want public static properties. The problem is GetProperties() returns both static and instance public properties. Anyone have an idea how to best approach this problem?

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

Note, I sort the list since GetProperties() does not specify any type of ordering, and ordering is important to me.

Use the other overload of GetProperties , which allows you to specify binding flags such as BindingFlags.Instance .

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

只是指出其他答案的附录-如果您不想继承属性,也可以使用BindingFlags.DeclaredOnly

Yep, you need to set the binding flags in the constructor. The binding flags specify flags that control binding and the way in which the search for members and types is conducted by reflection. Take a look at the following for more information:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM