属性继承与反思

时间:2010-07-21 15:56:27

标签: c# reflection inheritance attributes custom-attributes

我创建了一个自定义属性来装饰我想在运行时查询的多个类:

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

    public string Name
    {
        get;
        private set;
    }
}

这些类中的每一个都派生自一个抽象基类:

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

public class DerivedControl : ExampleContentControl
{
    // class contents here
}

我是否需要将此属性放在每个派生类上,即使我将其添加到基类中?该属性被标记为可继承,但是当我执行查询时,我只看到基类而不是派生类。

来自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>() };

谢谢, WTS

1 个答案:

答案 0 :(得分:3)

我按原样运行了你的代码,得到了以下结果:

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

所以它似乎有效...你确定其他事情还没有发生?