c# - 是否有可能知道属于某个类或其父类的属性

标签 c# reflection

public class Parent
{
    public virtual DateTime DateCreated
    {
      get;
      set;
    }
}

public class Child:Parent
{
......
}

  Type type = typeof(Child);

 //PropertyInfo DateTime = type.GetProperty("DateCreated"); 

有没有办法知道属性“DateCreated”是父属性而不是子属性。

最佳答案

您可以查看属性信息的DeclaringType值并查看它是否与 Child 类型匹配。如果不匹配,则您知道它已在父级上声明。

Type type = typeof(Child);
PropertyInfo dateTimeProperty = type.GetProperty("DateCreated"); 

bool declaredByParentClass = dateTimeProperty.DeclaringType != typeof(Child);

或者,您可以使用 overload of GetProperty检索 在类型 Child 上声明的属性:

Type type = typeof(Child);
PropertyInfo dateTimeProperty = type.GetProperty("DateCreated", BindingFlags.DeclaredOnly | BindingFlags.Public);

bool declaredByParentClass = dateTimeProperty == null;

如果您只是想检查它是否是从父类声明的,您可以使用第二种方法。但是,我怀疑即使该属性是在父级上声明的,您仍想对该属性执行某些操作,如果是这样,您将希望使用第一种方法来避免使用不同的绑定(bind)标志检索该属性两次。

关于c# - 是否有可能知道属于某个类或其父类的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17950725/

相关文章:

c# - ML.Net 0.7 - 获取多类分类的分数和标签

c# - 递归获取标有属性的属性

c# - 为什么十进制最小值不转换为字符串?

c# - MSDeploy - 允许参数在 parameters.xml 中是可选的/为空的

c# - Fastmember 访问非公共(public)属性

java - 用内部类注释类

c# - 找到正确的线程来调用方法而不会失败

c# - 使用反射转换为通用类型对象

c# - 将嵌套循环重构为单个 LINQ 查询

c# - 有人可以解释此Linq查询吗?