2012-04-12 179 views
0
Finding an enum value by its Description Attribute

檢索枚舉

我得到MyEnum的描述從用戶選擇的複選框, 我必須要找到價值和保存

可能重複的枚舉給定描述的價值。有人可以幫助我如何找到枚舉定描述

public enum MyEnum 
{ 
    [Description("First One")] 
    N1, 
    [Description("Here is another")] 
    N2, 
    [Description("Last one")] 
    N3 
} 

例如,我將在這裏給出的值是另一個我不得不返回N1,當我收到最後一個我不得不返回N3。

我只需要做的How to get C# Enum description from value?相反

有人能幫助我嗎?

+0

SOMETYPE測試=(SOMETYPE)Enum.Parse(typeof運算(SOMETYPE), 「三」); – helpme 2012-04-12 15:36:29

+0

但有沒有更簡單的方法? – helpme 2012-04-12 15:40:45

+2

比將答案中的代碼複製到項目中更簡單,然後只是_using_它?聽起來對我來說很容易。 – 2012-04-12 15:42:37

回答

1

像這樣:

// 1. define a method to retrieve the enum description 
public static string ToEnumDescription(this Enum value) 
{ 
    FieldInfo fi = value.GetType().GetField(value.ToString()); 

    DescriptionAttribute[] attributes = 
     (DescriptionAttribute[])fi.GetCustomAttributes(
     typeof(DescriptionAttribute), 
     false); 

    if (attributes != null && 
     attributes.Length > 0) 
     return attributes[0].Description; 
    else 
     return value.ToString(); 
} 

//2. this is how you would retrieve the enum based on the description: 
public static MyEnum GetMyEnumFromDescription(string description) 
{ 
    var enums = Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>(); 

    // let's throw an exception if the description is invalid... 
    return enums.First(c => c.ToEnumDescription() == description); 
} 

//3. test it: 
var enumChoice = EnumHelper.GetMyEnumFromDescription("Third"); 
Console.WriteLine(enumChoice.ToEnumDescription());