从属性创建枚举

发布于 2024-12-14 23:44:51 字数 547 浏览 2 评论 0原文

我使用自己的实体属性来标记我的枚举,用于将枚举映射到案例管理系统中的相应字段。

从枚举值获取正确的字符串工作正常,但如何从字符串生成枚举?

我首先这样做:

foreach (var fieldInfo in enumType.GetFields())
{
    var attribute = (EntityNameAttribute)fieldInfo
        .GetCustomAttributes(typeof (EntityNameAttribute), false)
        .FirstOrDefault();

    if (attribute == null)
        continue;

    if (attribute.Name != name)
        continue;

    //got a match. But now what?
}

但是如何从字段中获取正确的值?我可以只使用 fieldInfo.GetValue 吗?如果是这样,我应该使用什么实例?枚举应该被视为静态类型吗?

I'm marking my enums with an own entity attribute used to map the enums to the corresponding field in a case management system.

Getting the correct string from an enum value works fine, but how can I generate an enum from a string?

I started by doing this:

foreach (var fieldInfo in enumType.GetFields())
{
    var attribute = (EntityNameAttribute)fieldInfo
        .GetCustomAttributes(typeof (EntityNameAttribute), false)
        .FirstOrDefault();

    if (attribute == null)
        continue;

    if (attribute.Name != name)
        continue;

    //got a match. But now what?
}

But how do I get the proper value from a field? Can I just use fieldInfo.GetValue? If so, what instance should I use? Should the enum be treated as a static type?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

时光沙漏 2024-12-21 23:44:51

是的,您可以使用:

object value = fieldInfo.GetValue(null);

它们实际上只是静态只读字段。请注意,不是从字符串中获取枚举...但如果您确实需要这样做,则可以使用Enum.Parse

需要注意的一件事 - 如果您使用 .NET 3.5,则可以使用 LINQ 简化整个代码:(

var values = from field in enumType.GetFields()
             from EntityNameAttribute attribute in 
                   field.GetCustomAttributes((typeof(EntityNameAttribute), false)
             where attribute.Name == name
             select field.GetValue(null);

假设如果定义了正确类型的多个属性,则您不在乎哪一个有正确的名字,并且只有一个拥有正确的名字。)

Yes, you can use:

object value = fieldInfo.GetValue(null);

They're just static readonly fields, effectively. Note that that isn't getting an enum from a string... but if you do need to do that, you can use Enum.Parse.

One thing to note - if you're using .NET 3.5, your whole code can be simplified with LINQ:

var values = from field in enumType.GetFields()
             from EntityNameAttribute attribute in 
                   field.GetCustomAttributes((typeof(EntityNameAttribute), false)
             where attribute.Name == name
             select field.GetValue(null);

(That's assuming that if there are multiple attributes of the right type defined, you don't care which one has the right name, and only one will have the right name.)

顾挽 2024-12-21 23:44:51

是的,它可以被视为静态类型:

string enumString = fieldInfo.GetValue(null).ToString();

可以工作

Yes, it can be treated as a static type:

string enumString = fieldInfo.GetValue(null).ToString();

will work

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文