Domanda

Ho bisogno di essere in grado di recuperare Attributi personalizzati di una classe da un metodo nella sua classe di base. In questo momento sto facendo tramite un metodo statico protetta nella classe base con la seguente implementazione (la classe può avere più istanze dello stesso attributo applicate):

//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];
}

Io lo chiamo da una classe derivata nel seguente modo:

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

        var attribute = GetCustomAttribute(2);

     }

}

Idealmente mi piacerebbe essere in grado di chiamare questo dal contructor e cache i risultati.

Grazie.

PS

Mi rendo conto che non è garantito GetCustomAttributes di restituirli rispetto alla fine lessicale.

È stato utile?

Soluzione

Se è stato utilizzato metodi di istanza, piuttosto che metodi statici, si potrebbe chiamare this.GetType (), anche dalla classe base.

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

E 'più semplice, e compie il caching nel costruttore che si speravano.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top