如何反映应用于枚举类型本身的自定义属性
我有一个自定义属性,我想将其应用于枚举类型本身,但我无法识别正确的路径来获取正确的 *Info 以便公开该属性。
像这样的事情,
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
我熟悉从枚举值反映 DescriptionAttribute 的更“常规”方法。我经常做这样的事情,没问题。如以下类型的情况。
public enum MyEnumType {
[Description("My First Value")]
First,
[Description("My Second Value")]
Second,
}
我确信这是显而易见的,但我不知道这是否可能。
I've got a custom attribute that I want to apply to an enum type itself, but I'm having trouble identifying the correct path to get at the proper *Info in order to expose the attribute.
Something like this
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class MyCustAttribute : Attribute {}
[MyCust()]
[MyCust()]
[MyCust()]/*...and so on...*/
public enum MyEnumType{}
I am familiar with the more "customary" methods of reflecting say a DescriptionAttribute from an enumerated value. I do that sort of thing all the time, no problem. As in the following type case.
public enum MyEnumType {
[Description("My First Value")]
First,
[Description("My Second Value")]
Second,
}
I'm sure it's obvious, but I fail to see whether this is possible.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以像这样迭代
enum
类型的自定义属性:在此示例中,
GetCustomAttributes
返回一个object
数组。我们使用foreach
循环的功能来转换为我们知道数组元素包含的类型,因为这就是我们所要求的:MyCustAttribute
。由于您的自定义属性中还没有任何有趣的内容,因此我们只是选择打印出类型的名称。显然,您会用该类型的真实实例做一些更令人兴奋的事情。
You can iterate over your custom attributes of an
enum
type like this:In this example,
GetCustomAttributes
returns an array ofobject
. We use the ability of aforeach
loop to cast up to the type we know the array elements contain because that's what we asked for:MyCustAttribute
.Since your custom attribute doesn't have anything interesting in it yet, we just chose to print out the name of the type. You'll obviously do something more exciting with your real instance of the type.