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

标签 c# reflection

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

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/

相关文章:

java反射获取特定声明的字段值作为String

java - 具有匿名类的 CGLib 增强器

c# - 为什么 Assembly.GetType() 不适用于泛型类型实例?

c# - C# 的印地语文本到英语音译

c# - 将 Javascript 对象数组传递到 MVC3 Controller 时遇到问题,无法与 WCF 服务一起使用,有什么想法吗?

c# - JSON反序列化为动态后无法访问属性

objective-c - 将方法的所有参数传递到 NSLog

c# - 在 File.WriteAllText 中使用 unicode 时出现问题

c# - 什么是 "static"类?

c# - 从 Windows NT 设备路径转换为驱动器盘符路径