如何调用基类GetCustomAttributes?
-
11-09-2019 - |
题
我需要能够检索从在它的基类的方法的类的自定义属性。现在我通过结合下面的实施的基类被保护的静态方法做(类都可以应用相同的属性的多个实例):
//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不能保证相对于词法顺序返回它们。
解决方案
如果您使用的实例方法而不是静态的方法,可以调用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];
}
}
所以,很简单,并实现在你所希望看到的构造缓存。
不隶属于 StackOverflow