6

実行時にクエリを実行する多くのクラスを装飾するカスタム属性を作成しました。

[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
}

この属性を基本クラスに追加したとしても、各派生クラスにこの属性を配置する必要がありますか? 属性は継承可能としてマークされていますが、クエリを実行すると、基本クラスのみが表示され、派生クラスは表示されません。

別のスレッドから:

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

4

1 に答える 1

3

コードをそのまま実行したところ、次の結果が得られました。

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

うまくいっているようです... 他に何かが起こっていないのですか?

于 2010-07-21T16:02:22.130 に答える