【问题标题】:Attribute Inheritance and Reflection属性继承与反射
【发布时间】:2011-03-19 02:13:44
【问题描述】:

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

[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

【问题讨论】:

    标签: c# reflection inheritance attributes custom-attributes


    【解决方案1】:

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

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

    所以它似乎工作......你确定没有其他事情发生吗?

    【讨论】:

    • 尝试将派生类放入另一个项目,引用第一个。如果我将派生类放在与基类相同的命名空间中,它确实可以工作。
    • 好吧,想通了一半 - 调用 LINQ 查询时尚未加载其他程序集。我想问题就变成了,“如何获取与我的可执行文件关联的所有程序集(即,我应该用什么替换 AppDomain.CurrentDomain.GetAssemblies() 调用)?”
    • 对,这是有道理的……您需要找到某种方法来强制加载所有可能重要的程序集。这实际上取决于您的应用程序的结构。例如,如果您的所有程序集都是从应用程序运行的文件夹加载的,您可以扫描并强制加载。如果您正在做任何奇特的事情,例如重定向程序集负载……那就更棘手了。如果您提前知道您希望出现哪些程序集,那么最简单的方法就是在每个程序集中引用某种类型。
    • 是的,没错。我想我是希望避免“预加载”的事情,但也许没有一种好的、干净的方式来做到这一点。
    • 好吧,如果您要扫描已加载的程序集,那么这就是您的选择。如果您只想扫描程序集而不将其实际加载到应用程序域中,您也可以这样做...
    猜你喜欢
    • 2011-03-01
    • 2012-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多