简体   繁体   中英

C# Reflection - GetCustomAttributes for Type gets attribute from parent class

Let's say I have two classes, the base class has a custom attribute:

[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; }
}

When I'm working with inherited class, like

// member.DeclaringType is InheritedModel 

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

I expect this should be false because InheritedModel has not MyAttribute attribute directly.

It it correct behaviour? How can I divide parents and inheritors in condition above?

GetCustromAttributes has an overload which lets you specify if you want to search ancestor classes as well.

It seems to default to true (though it doesn't say in the docs) so try passing false

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM