繁体   English   中英

从属性创建枚举

[英]Create enum from an attribute

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

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

我首先这样做:

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吗? 如果是这样,我应该使用哪个实例? 应该将枚举视为静态类型吗?

是的,您可以使用:

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);

(这是假设,如果定义的正确类型的多个属性,你不在乎哪一个具有正确的名称,只有一个才会有正确的名称。)

是的,可以将其视为静态类型:

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

将工作

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM