2

基本クラスのメソッドからクラスのカスタム属性を取得できる必要があります。現在、次の実装を使用して、基本クラスの保護された静的メソッドを介してそれを行っています(クラスには、同じ属性の複数のインスタンスを適用できます)。

//Defined in a 'Base' class
protected static CustomAttribute GetCustomAttribute(int n) 
{
        return new StackFrame(1, false) //get the previous frame in the stack
                                        //and thus the previous method.
            .GetMethod()
            .DeclaringType
            .GetCustomAttributes(typeof(CustomAttribute), false)
            .Select(o => (CustomAttribute)o).ToList()[n];
}

したがって、派生クラスから呼び出します。

[CustomAttribute]
[CustomAttribute]
[CustomAttribute]
class Derived: Base
{
    static void Main(string[] args)
    {

        var attribute = GetCustomAttribute(2);

     }

}

理想的には、コンストラクターからこれを呼び出して結果をキャッシュすることができます。

ありがとう。

PS

GetCustomAttributes が字句順序に関してそれらを返すことが保証されていないことを認識しています。

4

1 に答える 1

9

静的メソッドではなくインスタンス メソッドを使用した場合は、基本クラスからでも this.GetType() を呼び出すことができます。

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true)]
class CustomAttribute : Attribute
{}

abstract class Base
{
    protected Base()
    {
        this.Attributes = Attribute.GetCustomAttributes(this.GetType(), typeof(CustomAttribute))
            .Cast<CustomAttribute>()
            .ToArray();
    }

    protected CustomAttribute[] Attributes { get; private set; }
}

[Custom]
[Custom]
[Custom]
class Derived : Base
{
    static void Main()
    {
        var derived = new Derived();
        var attribute = derived.Attributes[2];
    }
}

それはより簡単で、あなたが望んでいたコンストラクターでのキャッシュを実現します。

于 2009-12-01T20:27:24.333 に答える