2009-12-01 46 views
1

我需要能夠從其基類中的方法中檢索類的自定義屬性。現在,我通過與下面的實現基類的一個受保護的靜態方法做它(類都可以應用同一個屬性的多個實例):如何從基類調用GetCustomAttributes?

//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不能保證相對於詞法順序返回。

回答

8

如果您使用實例方法而不是靜態方法,則可以調用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]; 
    } 
} 

它更簡單,並在您希望的構造函數中完成緩存。

+0

謝謝。這是一個很好的,但我確實需要這個爲單身人士工作。看着堆棧框架感覺不舒服,但它保持了API的清潔,所以我現在堅持下去。我接受了你的回答,因爲它可以幫助別人。 – 2009-12-02 17:46:03