2009-06-23 62 views
4

我具有表示系統中的所有材料彙編代碼的枚舉:如何從描述中獲得枚舉值?

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

在傳統代碼在系統的另一部分,我有標記有相匹配的枚舉描述的字符串對象。鑑於其中的一個字符串,獲取枚舉值的最簡單方法是什麼?我設想是這樣的:

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

回答

8

你會需要通過枚舉所有的靜態字段進行迭代(這就是他們如何存儲在反射)找到爲每一個Description屬性...當你發現了正確的一個,獲得該領域的價值。

例如:(這是一般只是爲了重複使用於不同的枚舉)

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

顯然,你會想,如果你這樣做,甚至略有頻繁緩存的說明如:

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"); 
    } 
} 
+1

哎,真的很希望爲「這裏有一個方便的功能就像一個詞典<>的說明和值之間」。也許我會建立一個靜態保存該字典的類,並在第一次需要時填充它...? – 2009-06-23 15:26:22

+0

是的 - 你需要的核心部分是我的答案,它給出了描述。哦,它的東西...我現在寫。掛在:) – 2009-06-23 15:29:40

0
public EAssemblyUnit FromDescription(string AU) 
{ 
    EAssemblyUnit eAU = Enum.Parse(typeof(EAssemblyUnit), AU, true); 
    return eAU; 
} 
0

您也可以使用Humanizer˚F或者那個。要獲得描述你可以使用:

EAssemblyUnit.eUCAL1.Humanize(); 

,並得到枚舉從描述回你可以使用

"UCAL1".DehumanizeTo<EAssemblyUnit>(); 

免責聲明:我Humanizer的創造者。