如何找出如果属性是从基类继承或宣布出来的? [英] How to find out if property is inherited from a base class or declared in derived?

查看:126
本文介绍了如何找出如果属性是从基类继承或宣布出来的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从抽象类派生的类。得到一个类型派生类中我想找出哪些属性是从抽象类继承和被宣布在派生类中。

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



所以,我想快点找出CommonParam是一种遗传参数和标识,名称是PARAMS在MsClass声明。有什么建议?

So, I would like to quickly find out that CommonParam is an inherited parameter and Id, Name are params declared in MsClass. Any suggestions?

要使用声明的尝试只会标志返回我空的PropertyInfo数组

Attempt to use declared only flag returns me empty PropertyInfo array

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

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



However, GetProperties() returns all properties of inheritance hierarchy.

type.GetProperties()

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

我错过了什么?

推荐答案

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

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);

这篇关于如何找出如果属性是从基类继承或宣布出来的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆