代码之家  ›  专栏  ›  技术社区  ›  Wonko the Sane

属性继承和反射

  •  6
  • Wonko the Sane  · 技术社区  · 15 年前

    我创建了一个自定义属性来修饰运行时要查询的许多类:

    [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 回复  |  直到 12 年前
        1
  •  3
  •   Nader Shirazie    15 年前

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

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

    所以它似乎有效…你确定别的事情不会发生吗?

    推荐文章