c# - 如何排除父类的属性

标签 c# inheritance reflection

假设我有以下两个类。

  public class Father
    {
        public int Id { get; set; }
        public int Price { get; set; } 
    }
    public class Child: Father
    {
        public string Name { get; set; }
    }

我如何知道特定属性是父属性(继承)还是子属性?

我试过了

var childProperties = typeof(Child).GetProperties().Except(typeof(Father).GetProperties());

但似乎 Except 没有检测父属性和子继承属性的相等性。

最佳答案

GetProperties 上使用重载接受 BindingFlags .在 PublicInstance 标志旁边包含 DeclaredOnly 标志,一切就绪:

var childProperties = typeof(Child)
            .GetProperties(
                BindingFlags.Public | 
                BindingFlags.Instance | 
                BindingFlags.DeclaredOnly  // to search only the properties declared on 
                                           // the Type, not properties that 
                                           // were simply inherited.
            );

这将返回一个属性,名称。

exclude inherited properties debug

请注意,使用此解决方案您无需检查 DeclaringType。

关于c# - 如何排除父类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060658/

相关文章:

c# - 适用于 Windows 7 x64 的 IrDa API

java - 当一个抽象类扩展一个具体类时,继承的成员会变成抽象的吗?

java - 无法通过反射实例化类

c# - 某些项目无法加载 PDB 文件

c# - 为什么默认情况下静态字段为空?

c# - LINQ-to-sql 抽象类中的映射表达式

.net - 以编程方式访问 .NET 类型的 CIL

java - 获取字段名称

c# - EF Code First 使用 IEnumerable <> 进行递归查询?

C++ 为什么继承不起作用?