简体   繁体   English

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

[英]How to find out if property is inherited from a base class or declared in derived?

I have a class that is derived from an abstract class. 我有一个派生自抽象类的类。 Getting a type of a derived class I want to find out which properties are inherited from abstract class and which were declared in the derived class. 获取派生类的类型我想找出哪些属性是从抽象类继承的,哪些属性是在派生类中声明的。

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"
};

So, I would like to quickly find out that CommonParam is an inherited parameter and Id, Name are params declared in MsClass. 所以,我想快速找出CommonParam是一个继承参数,Id,Name是在MsClass中声明的参数。 Any suggestions? 有什么建议么?

Attempt to use declared only flag returns me empty PropertyInfo array 尝试使用仅声明的标志返回空PropertyInfo数组

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

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

However, GetProperties() returns all properties of inheritance hierarchy. 但是,GetProperties()返回继承层次结构的所有属性。

type.GetProperties()

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

Did I miss something? 我错过了什么?

You can specify Type.GetProperties ( BindingFlags.DeclaredOnly ) to get the properties that are defined in the derived class. 您可以指定Type.GetProperties ( BindingFlags.DeclaredOnly )以获取在派生类中定义的属性。 If you then call GetProperties on the base class, you can get the properties defined in the base class. 如果随后在基类上调用GetProperties ,则可以获取基类中定义的属性。


In order to fetch the public properties from your class, you could do: 要从您的班级中获取公共属性,您可以执行以下操作:

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

You can check based on the DeclaringType as below: 您可以根据DeclaringType进行检查,如下所示:

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

To get properties from base class you can call similarly: 要从基类获取属性,您可以类似地调用:

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

This may helps: 这可能有助于:

Type type = typeof(MsClass);

Type baseType = type.BaseType;

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

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

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