C# 如何从基类调用GetCustomAttributes?

C# 如何从基类调用GetCustomAttributes?,c#,reflection,inheritance,custom-attributes,C#,Reflection,Inheritance,Custom Attributes,我需要能够从基类中的方法检索类的自定义属性。现在,我通过基类中的一个受保护的静态方法执行此操作,并使用以下实现(该类可以应用同一属性的多个实例): 我从派生类中调用它: [CustomAttribute] [CustomAttribute] [CustomAttribute] class Derived: Base { static void Main(string[] args) { var attribute = GetCustomAttribute(2);

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

我从派生类中调用它:

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

        var attribute = GetCustomAttribute(2);

     }

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

谢谢

PS


我意识到GetCustomAttributes并不能保证按照词法顺序返回它们。

如果使用实例方法而不是静态方法,则可以调用此.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];
    }
}
[AttributeUsage(AttributeTargets.Class,AllowMultiple=true,Inherited=true)]
类CustomAttribute:属性
{}
抽象类基
{
保护基()
{
this.Attributes=Attribute.GetCustomAttributes(this.GetType(),typeof(CustomAttribute))
.Cast()
.ToArray();
}
受保护的CustomAttribute[]属性{get;private set;}
}
[海关]
[海关]
[海关]
派生类:基
{
静态void Main()
{
var派生=新派生();
var-attribute=derived.Attributes[2];
}
}

它更简单,可以在构造函数中完成您希望的缓存。

如果使用实例方法而不是静态方法,则可以调用此.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];
    }
}
[AttributeUsage(AttributeTargets.Class,AllowMultiple=true,Inherited=true)]
类CustomAttribute:属性
{}
抽象类基
{
保护基()
{
this.Attributes=Attribute.GetCustomAttributes(this.GetType(),typeof(CustomAttribute))
.Cast()
.ToArray();
}
受保护的CustomAttribute[]属性{get;private set;}
}
[海关]
[海关]
[海关]
派生类:基
{
静态void Main()
{
var派生=新派生();
var-attribute=derived.Attributes[2];
}
}

它更简单,可以在构造函数中完成您希望的缓存。

谢谢。这是个好主意,但我确实需要这个来为单身人士工作。查看堆栈框架感觉很粗糙,但它保持了API的干净,所以我现在就坚持使用它。我接受了你的回答,因为它可能会帮助别人。谢谢。这是个好主意,但我确实需要这个来为单身人士工作。查看堆栈框架感觉很粗糙,但它保持了API的干净,所以我现在就坚持使用它。我接受了你的回答,因为它可能会帮助别人。