如何确定属性是从基类继承的还是在派生类中声明的

本文关键字:声明 派生 继承 何确定 属性 基类 | 更新日期: 2023-09-27 18:06:45

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

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}

我错过什么了吗?

如何确定属性是从基类继承的还是在派生类中声明的

您可以指定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);

您可以根据DeclaringType进行检查,如下所示:

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

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

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

这可能有帮助:

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