Inheritance and reflection of attributes

I created a custom attribute to decorate several classes that I want to request at runtime:

[AttributeUsage(AttributeTargets.Class, AllowMultiple=false, Inherited=true)] public class ExampleAttribute : Attribute { public ExampleAttribute(string name) { this.Name = name; } public string Name { get; private set; } } 

Each of these classes comes from an abstract base class:

 [Example("BaseExample")] public abstract class ExampleContentControl : UserControl { // class contents here } public class DerivedControl : ExampleContentControl { // class contents here } 

Do I need to put this attribute on every derived class, even if I add it to the base class? The attribute is marked as inherited, but when I execute the request, I see only the base class, not the derived classes.

From another thread :

 var typesWithMyAttribute = from a in AppDomain.CurrentDomain.GetAssemblies() from t in a.GetTypes() let attributes = t.GetCustomAttributes(typeof(ExampleAttribute), true) where attributes != null && attributes.Length > 0 select new { Type = t, Attributes = attributes.Cast<ExampleAttribute>() }; 

Thanks, WTS

+6
inheritance reflection c # attributes custom-attributes
source share
1 answer

I ran your code as is and got the following result:

 { Type = ConsoleApplication2.ExampleContentControl, Attributes = ConsoleApplication2.ExampleAttribute[] } { Type = ConsoleApplication2.DerivedControl, Attributes = ConsoleApplication2.ExampleAttribute[] } 

So it looks like you are working ... Are you sure something else is not happening?

+3
source share

All Articles