【问题标题】:How do I call GetCustomAttributes from a Base Class?如何从基类调用 GetCustomAttributes?
【发布时间】:2010-12-22 03:36:12
【问题描述】:

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

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

【问题讨论】:

    标签: c# reflection inheritance custom-attributes


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢。这很好,但我确实需要这个来为单身人士工作。看着堆栈框架感觉很骇人,但它使 API 保持干净,所以我现在会坚持下去。我接受了您的回答,因为它可能对其他人有所帮助。
    猜你喜欢
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-05
    • 1970-01-01
    • 1970-01-01
    • 2013-09-23
    相关资源
    最近更新 更多