我需要能够从其基类中的方法检索类的自定义属性。现在,我通过基类中的受保护静态方法执行此操作,实现如下(该类可以应用相同属性的多个实例):
//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);
}
}
理想情况下,我可以从构造函数调用它并缓存结果。
谢谢。
附言
我意识到 GetCustomAttributes 不能保证根据词汇顺序返回它们。