如何从基类调用GetCustomAttributes?

Rod*_*man 1 c# reflection inheritance custom-attributes

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

//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];
}
Run Code Online (Sandbox Code Playgroud)

我这样从派生类中调用它:

[CustomAttribute]
[CustomAttribute]
[CustomAttribute]
class Derived: Base
{
    static void Main(string[] args)
    {

        var attribute = GetCustomAttribute(2);

     }

}
Run Code Online (Sandbox Code Playgroud)

理想情况下,我可以从构造函数中调用它并缓存结果.

谢谢.

PS

我意识到GetCustomAttributes不保证在词法顺序方面返回它们.

Dan*_*ing 8

如果使用实例方法而不是静态方法,则可以调用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];
    }
}
Run Code Online (Sandbox Code Playgroud)

它更简单,并在您希望的构造函数中完成缓存.