2012-04-12 88 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());