【问题标题】:How to find out if property is inherited from a base class or declared in derived?如何确定属性是从基类继承还是在派生中声明?
【发布时间】:2013-04-01 16:00:55
【问题描述】:

我有一个派生自抽象类的类。获取派生类的类型我想找出哪些属性是从抽象类继承的,哪些是在派生类中声明的。

public abstract class BaseMsClass
{
    public string CommonParam { get; set; }
}

public class MsClass : BaseMsClass
{
    public string Id { get; set; }
    public string Name { get; set; }

    public MsClass()
    { }
}

var msClass = new MsClass
{
    Id = "1122",
    Name = "Some name",
    CommonParam = "param of the base class"
};

所以,我想快速发现 CommonParam 是一个继承参数,而 Id、Name 是在 MsClass 中声明的参数。有什么建议吗?

尝试使用仅声明的标志返回空的 PropertyInfo 数组

Type type = msClass.GetType();
type.GetProperties(System.Reflection.BindingFlags.DeclaredOnly)

-->{System.Reflection.PropertyInfo[0]}

但是,GetProperties() 返回继承层次结构的所有属性。

type.GetProperties()

-->{System.Reflection.PropertyInfo[3]}
-->[0]: {System.String Id}
-->[1]: {System.String Name}
-->[2]: {System.String CommonParam}

我错过了什么吗?

【问题讨论】:

    标签: c# reflection


    【解决方案1】:

    您可以指定Type.GetProperties(BindingFlags.DeclaredOnly) 来获取派生类中定义的属性。如果再在基类上调用GetProperties,就可以得到基类中定义的属性。


    为了从你的类中获取公共属性,你可以这样做:

    var classType = typeof(MsClass);
    var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
    var inheritedProps = classType.BaseType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
    

    【讨论】:

    • 不知何故,这种方法没有给出预期的结果。问题已更新。
    • @Maxim 你需要type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)。 +1 给 Reed,希望他能更新一下答案
    【解决方案2】:

    您可以根据DeclaringType查看如下:

    var pros = typeof(MsClass).GetProperties()
                              .Where(p => p.DeclaringType == typeof(MsClass));
    

    要从基类中获取属性,您可以类似地调用:

    var pros = typeof(MsClass).GetProperties()
                              .Where(p => p.DeclaringType == typeof(BaseMsClass));
    

    【讨论】:

      【解决方案3】:

      这可能会有所帮助:

      Type type = typeof(MsClass);
      
      Type baseType = type.BaseType;
      
      var baseProperties = 
           type.GetProperties()
                .Where(input => baseType.GetProperties()
                                         .Any(i => i.Name == input.Name)).ToList();
      

      【讨论】:

      • +1 绝对有效,但不是很优雅。预计应该已经实现了一些东西来支持所需的请求。
      猜你喜欢
      • 1970-01-01
      • 2016-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      • 2022-12-11
      相关资源
      最近更新 更多