假设我有以下两个类。
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
.在 Public
和 Instance
标志旁边包含 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.
);
这将返回一个属性,名称。
请注意,使用此解决方案您无需检查 DeclaringType。
关于c# - 如何排除父类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48060658/