C#反射-GetCustomAttributes for Type从父类获取属性

C#反射-GetCustomAttributes for Type从父类获取属性,c#,asp.net-web-api,system.reflection,C#,Asp.net Web Api,System.reflection,假设我有两个类,基类有一个自定义属性: [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;

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

[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
属性

这是正确的行为吗?在上述情况下,如何划分父类和继承类?

有一个重载,允许您指定是否也要搜索祖先类

它似乎默认为
true
(虽然文档中没有说明),所以请尝试传递
false

member.DeclaringType.GetCustomAttributes(typeof(MyAttribute), false).Any()
有一个重载,允许您指定是否也要搜索祖先类

它似乎默认为
true
(虽然文档中没有说明),所以请尝试传递
false

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

您可以通过在的属性设置中设置
Inherited=false
来更改此行为。您可以通过在的属性设置中设置
Inherited=false
来更改此行为