如果使用实例方法而不是静态方法,则可以调用此.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];
}
}
它更简单,并且在您希望的构造函数中实现缓存。