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不能保證相對於詞法順序返回。
謝謝。這是一個很好的,但我確實需要這個爲單身人士工作。看着堆棧框架感覺不舒服,但它保持了API的清潔,所以我現在堅持下去。我接受了你的回答,因爲它可以幫助別人。 – 2009-12-02 17:46:03