2

我需要能够从其基类中的方法检索类的自定义属性。现在,我通过基类中的受保护静态方法执行此操作,实现如下(该类可以应用相同属性的多个实例):

//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 不能保证根据词汇顺序返回它们。

4

1 回答 1

9

如果您使用实例方法而不是静态方法,则可以调用 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];
    }
}

它更简单,并且完成了您希望的构造函数中的缓存。

于 2009-12-01T20:27:24.333 回答