如何排除父类的属性

Yah*_*ein 7 c# reflection inheritance

假设我有以下两个类.

  public class Father
    {
        public int Id { get; set; }
        public int Price { get; set; } 
    }
    public class Child: Father
    {
        public string Name { get; set; }
    }
Run Code Online (Sandbox Code Playgroud)

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

我试过了

var childProperties = typeof(Child).GetProperties().Except(typeof(Father).GetProperties());
Run Code Online (Sandbox Code Playgroud)

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

luc*_*cky 7

试试这个;

var childPropertiesOnly = typeof(Child)
         .GetProperties()
         .Where(x => x.DeclaringType != typeof(Father))
         .ToList();
Run Code Online (Sandbox Code Playgroud)


ren*_*ene 7

使用GetProperties接受的重载BindingFlags.包括DeclaredOnly旁边的标志PublicInstance标志和你所有的设置:

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.
            );
Run Code Online (Sandbox Code Playgroud)

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

排除继承的属性debug

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


Dan*_*ite 5

检查DeclaringType房产PropertyInfo.这应该告诉你足够的信息.