C#反射 - 类型的getCustomatTributes从父类属于属性



假设我有两个类,基类有一个自定义属性:

[MyAttribute]
public class BaseModel
{
    public string Id { get; set; }
    public string Name { get; set; }
}
public class InheritedModel : BaseModel
{
    public string CompanyName { get; set; }
    public int Amount { get; set; }
}

当我与继承的班级合作时,例如

// member.DeclaringType is InheritedModel 
if (member.DeclaringType.GetCustomAttributes(typeof(MyAttribute)).Any())
{
   // returns true
}

我希望这应该是false,因为InheritedModel没有直接的MyAttribute属性。

它正确的行为?我如何在上面的状态下划分父母和继承者?

getCustromomattributes的过载,可以指定您是否也要搜索祖先类。

它似乎默认为true(尽管在文档中没有说(,因此请尝试通过false

member.DeclaringType.GetCustomAttributes(typeof(MyAttribute), false).Any()

最新更新