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

后端 未结 3 855
野的像风
野的像风 2021-02-05 07:28

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 dec

相关标签:
3条回答
  • 2021-02-05 08:06

    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();
    
    0 讨论(0)
  • 2021-02-05 08:29

    You can check based on the DeclaringType as below:

    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));
    
    0 讨论(0)
  • 2021-02-05 08:31

    You can specify Type.GetProperties(BindingFlags.DeclaredOnly) to get the properties that are defined in the derived class. If you then call GetProperties on the base class, you can get the properties defined in the base class.


    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);
    
    0 讨论(0)
提交回复
热议问题