Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Attribute Inheritance and Reflection

I have created a custom Attribute to decorate a number of classes that I want to query for 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 derive 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 each derived class, even if I add it to the base class? The attribute is marked as inheritable, but when I do the query, I only see the base class and 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

like image 310
Wonko the Sane Avatar asked Jul 21 '10 15:07

Wonko the Sane


1 Answers

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 seems to work... You sure something else isn't going on?

like image 150
Nader Shirazie Avatar answered Oct 20 '22 07:10

Nader Shirazie