C# - 检查枚举元素上属性是否存在

发布于 2024-12-25 08:18:14 字数 407 浏览 10 评论 0原文

我遇到如下情况:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

jJeQQOZ5 2025-01-01 08:18:14

据我所知,您必须从该字段获取属性。您可以使用:

var field = typeof(Header).GetField(value.ToString());
var old = field.IsDefined(typeof(OldProtocolAttribute), false);

或者获取整个数组:

var attributeType = typeof(OldProtocolAttribute);
var array = typeof(Header).GetFields(BindingFlags.Public |
                                     BindingFlags.Static)
                          .Where(field => field.IsDefined(attributeType, false))
                          .Select(field => (Header) field.GetValue(null))
                          .ToArray();

显然,如果您经常需要这样做,您可能希望缓存结果。

As far as I'm aware, you have to get the attribute from the field. You'd use:

var field = typeof(Header).GetField(value.ToString());
var old = field.IsDefined(typeof(OldProtocolAttribute), false);

Or to get a whole array:

var attributeType = typeof(OldProtocolAttribute);
var array = typeof(Header).GetFields(BindingFlags.Public |
                                     BindingFlags.Static)
                          .Where(field => field.IsDefined(attributeType, false))
                          .Select(field => (Header) field.GetValue(null))
                          .ToArray();

Obviously if you need this often, you may well want to cache the results.

数理化全能战士 2025-01-01 08:18:14

反射几乎是唯一可用的工具。不过查询还不错:

var oldFields = typeof(Header).GetFields(BindingFlags.Static | BindingFlags.Public).Select(field => Attribute.IsDefined(field, typeof(OldProtocolAttribute)));

Reflection is pretty much your only tool available for this. The query is not too bad though:

var oldFields = typeof(Header).GetFields(BindingFlags.Static | BindingFlags.Public).Select(field => Attribute.IsDefined(field, typeof(OldProtocolAttribute)));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文