C# - 检查枚举元素上属性是否存在
我遇到如下情况:
enum Header
{
Sync,
[OldProtocol] Keepalive,
Ping,
[OldProtocol] Auth,
[OldProtocol] LoginData
//...
}
我需要获取定义了 OldProtocolAttribute
的元素数组。我注意到 Attribute.IsDefined() 方法及其重载显然不支持这种情况。
我的问题是:
- 有没有一种方法可以在不使用解决方案的任何部分
typeof(Header).GetField()
的情况下解决问题? - 如果不是,解决这个问题的最佳方法是什么?
I've got a situation like the following:
enum Header
{
Sync,
[OldProtocol] Keepalive,
Ping,
[OldProtocol] Auth,
[OldProtocol] LoginData
//...
}
I need to obtain an array of elements on which the OldProtocolAttribute
is defined. I've noticed that the Attribute.IsDefined()
method and its overloads apparently don't support this kind of situation.
My question is:
- Is there a way to solve the problem without using in any part of the solution
typeof(Header).GetField()
? - If not, what's the most optimal way to solve it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我所知,您必须从该字段获取属性。您可以使用:
或者获取整个数组:
显然,如果您经常需要这样做,您可能希望缓存结果。
As far as I'm aware, you have to get the attribute from the field. You'd use:
Or to get a whole array:
Obviously if you need this often, you may well want to cache the results.
反射几乎是唯一可用的工具。不过查询还不错:
Reflection is pretty much your only tool available for this. The query is not too bad though: