我有一个派生自抽象类的类。获取派生类的类型 我想找出哪些属性是从抽象类继承的,哪些是在派生类中声明的。
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
,您可以获得基类中定义的属性。
为了从你的类中获取公共(public)属性,你可以这样做:
var classType = typeof(MsClass);
var classProps = classType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public);
var inheritedProps = classType.BaseType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
关于c# - 如何确定属性是从基类继承还是在派生类中声明?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15746854/