【问题标题】:Get all properties of current class and base class获取当前类和基类的所有属性
【发布时间】:2014-08-11 05:47:53
【问题描述】:

我有 2 个类(比如说“BaseItem”和“ChildItem”),它们有几个内部属性。在 BaseClass 中,我定义了一个方法,它应该用

读取所有这些属性
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this);

PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(this.GetType()); 

当我在“ChildItem”的实例中调用此方法时,我只获得“ChildItem”中定义的属性。我该怎么做才能获得“BaseItem”的属性?

问候

戴夫

【问题讨论】:

  • 为什么直接用TypeDescriptor而不是Type来获取道具?
  • 你可以看看这个:stackoverflow.com/questions/245055/…
  • 我也用 Type.GetProperties 试过这个。结果是一样的。只会返回“ChildItem”中定义的属性。
  • 您想要的属性是来自基本公共还是私有/受保护/内部?

标签: c# propertydescriptor


【解决方案1】:

对于内部属性(如问题 cmets 中所阐明的那样),虽然没有指明(它们是内部的),但您可以使用:

var internalProperties = GetType().GetProperties(
                            BindingFlags.Instance | 
                            BindingFlags.NonPublic |
                            BindingFlags.Public));

需要应用的是标志BindingFlags.NonPublic

【讨论】:

    【解决方案2】:

    您可以将其转换为 BaseItem 并单独执行 GetProperties()..

    【讨论】:

    • 这是我目前的解决方法。我遍历所有基类,直到达到指定的基类(“BaseItem)。但我真的很确定,有一个更快的解决方案可用;-)
    猜你喜欢
    • 1970-01-01
    • 2015-10-29
    • 2011-10-20
    • 1970-01-01
    • 2014-02-16
    • 2016-09-09
    • 2012-04-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多