如何从描述中获取枚举值? [英] How can I get an enum value from its description?

查看:343
本文介绍了如何从描述中获取枚举值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  public enum EAssemblyUnit 
{
[描述(UCAL1)]
eUCAL1,
[描述(UCAL1-3CP)]
eUCAL13CP,
[描述(UCAL40-3CP)]
eUCAL403CP,// ...
}

在另一个的旧代码中系统的一部分,我有对象标记与字符串匹配的枚举描述。给定这些字符串之一,获得枚举值最干净的方法是什么?我想像的是:

  public EAssemblyUnit FromDescription(string AU)
{
EAssemblyUnit eAU =我们发现具有匹配AU>
返回eAU;
}


解决方案

你需要迭代通过枚举的所有静态字段(这就是它们在反射中的存储方式),当找到正确的属性时,找到每个的描述属性...获取该字段的值。



例如:

  public static T GetValue< T>(string description)
{
foreach(typeof(T)中的var field .GetFields())
{
var descriptions =(DescriptionAttribute [])
field.GetCustomAttributes(typeof(DescriptionAttribute),false) ;
if(descript.Any(x => x.Description == description))
{
return(T)field.GetValue(null);
}
}
throw new SomeException(Description not found);
}

(这是通用的,只是为了使其可重用于不同的枚举。 p>

很明显,如果您稍微频繁地执行此操作,则可以缓存描述,例如:

  public static class DescriptionDictionary< T>其中T:struct 
{
private static readonly Dictionary< string,T> Map =
new Dictionary< string,T>();

static DescriptionDictionary()
{
if(typeof(T).BaseType!= typeof(Enum))
{
throw new ArgumentException只能使用枚举);
}
//可以用一个LINQ查询,不用承认...
foreach(typeof(T)中的var field).GetFields
(BindingFlags.Public | BindingFlags.Static ))
{
T value =(T)field.GetValue(null);
foreach((DescriptionAttribute [])中的var description in
field.GetCustomAttributes(typeof(DescriptionAttribute),false))
{
// TODO:
//多次
Map [description.Description] = value;
}
}
}

public static T GetValue(string description)
{
T ret;
if(Map.TryGetValue(description,out ret))
{
return ret;
}
throw new WhateverException(Description not found);
}
}


I have an enum representing all material assembly codes in the system:

public enum EAssemblyUnit
{
    [Description("UCAL1")]
    eUCAL1,
    [Description("UCAL1-3CP")]
    eUCAL13CP,
    [Description("UCAL40-3CP")]
    eUCAL403CP, // ...
}

In legacy code in another part of the system, I have objects labeled with strings that match the enum descriptions. Given one of those strings, what's the cleanest way to get the enum value? I envision something like:

public EAssemblyUnit FromDescription(string AU)
{
    EAssemblyUnit eAU = <value we find with description matching AU>
    return eAU;
}

解决方案

You'd need to iterate through all the static fields of the enum (that's how they're stored in reflection) finding the Description attribute for each one... when you spot the right one, get the value of the field.

For example:

public static T GetValue<T>(string description)
{
    foreach (var field in typeof(T).GetFields())
    {
        var descriptions = (DescriptionAttribute[]) 
               field.GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (descriptions.Any(x => x.Description == description))
        {
            return (T) field.GetValue(null);
        }
    }
    throw new SomeException("Description not found");
}

(This is generic just to make it reusable for different enums.)

Obviously you'd want to cache the descriptions if you're doing this even slightly frequently, e.g.:

public static class DescriptionDictionary<T> where T : struct
{
    private static readonly Dictionary<string, T> Map = 
        new Dictionary<string, T>();

    static DescriptionDictionary()
    {
        if (typeof(T).BaseType != typeof(Enum))
        {
            throw new ArgumentException("Must only use with enums");
        }
        // Could do this with a LINQ query, admittedly...
        foreach (var field in typeof(T).GetFields
                 (BindingFlags.Public | BindingFlags.Static))
        {
            T value = (T) field.GetValue(null);
            foreach (var description in (DescriptionAttribute[]) 
               field.GetCustomAttributes(typeof(DescriptionAttribute), false))
            {
                // TODO: Decide what to do if a description comes up
                // more than once
                Map[description.Description] = value;
            }
        }
    }

    public static T GetValue(string description)
    {
        T ret;
        if (Map.TryGetValue(description, out ret))
        {
            return ret;
        }
        throw new WhateverException("Description not found");
    }
}

这篇关于如何从描述中获取枚举值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆