繁体   English   中英

如何使用反射来获取对象实例的公共属性?

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

我在反思一个对象,只想要一个实例的公共属性,我不想要公共静态属性。 问题是GetProperties()返回静态和实例公共属性。 任何人都知道如何最好地解决此问题?

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

注意,我对列表进行排序是因为GetProperties()没有指定任何类型的排序,因此排序对我很重要。

使用GetProperties的其他重载 ,该重载允许您指定绑定标志,例如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

是的,您需要在构造函数中设置绑定标志。 绑定标志指定控制绑定的标志以及通过反射进行成员和类型搜索的方式。 请查看以下内容以获取更多信息:

BindingFlags枚举: http : //msdn.microsoft.com/zh-cn/library/system.reflection.bindingflags.aspx

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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