gpt4 book ai didi

c# - 如何从基类调用 GetCustomAttributes?

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:32 25 4
gpt4 key购买 nike

我需要能够从类的基类中的方法中检索类的自定义属性。现在,我通过基类中的 protected 静态方法使用以下实现来完成此操作(该类可以应用相同属性的多个实例):

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

最佳答案

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

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

关于c# - 如何从基类调用 GetCustomAttributes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1828346/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com