22

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

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}

我错过了什么?

4

3 回答 3

30

您可以指定获取在派生类中定义的属性。如果随后调用基类,则可以获取基类中定义的属性。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);
于 2013-04-01T16:03:12.027 回答
14

您可以根据DeclaringType以下情况进行检查:

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

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

var pros = typeof(MsClass).GetProperties()
                          .Where(p => p.DeclaringType == typeof(BaseMsClass));
于 2013-04-01T16:07:55.797 回答
3

这可能会有所帮助:

Type type = typeof(MsClass);

Type baseType = type.BaseType;

var baseProperties = 
     type.GetProperties()
          .Where(input => baseType.GetProperties()
                                   .Any(i => i.Name == input.Name)).ToList();
于 2013-04-01T16:13:17.007 回答