从属性创建枚举
我使用自己的实体属性来标记我的枚举,用于将枚举映射到案例管理系统中的相应字段。
从枚举值获取正确的字符串工作正常,但如何从字符串生成枚举?
我首先这样做:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您可以使用:
它们实际上只是静态只读字段。请注意,不是从字符串中获取枚举...但如果您确实需要这样做,则可以使用
Enum.Parse
。需要注意的一件事 - 如果您使用 .NET 3.5,则可以使用 LINQ 简化整个代码:(
假设如果定义了正确类型的多个属性,则您不在乎哪一个有正确的名字,并且只有一个将拥有正确的名字。)
Yes, you can use:
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:
(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.)
是的,它可以被视为静态类型:
可以工作
Yes, it can be treated as a static type:
will work