2012-08-14 97 views
0

得到DescriptionAttribute值我有一个枚举类型如何从枚举成员

public enum DataType:int 
    { 
     None = 0, 
     [Description("A")] 
     Alpha = 1, 
     [Description("N")] 
     Numeric, 
     [Description("AN")] 
     AlphaNumeric, 
     [Description("D")] 
     Date 
    } 

如何重新获取的,比如说,阿尔法的描述属性值。

EG(理想):DataType.Alpha.Attribute应该给“A”

+0

请参阅http://stackoverflow.com/questions/540241/exposing-the-descriptionattribute-of-enums-from-a-wcf-service中的评论。 – neontapir 2012-08-14 19:28:50

回答

5

使用此

private string GetEnumDescription(Enum value) 
{ 
    // Get the Description attribute value for the enum value 
    FieldInfo fi = value.GetType().GetField(value.ToString()); 
    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); 

    if (attributes.Length > 0) 
     return attributes[0].Description; 
    else 
     return value.ToString(); 
} 
2

我有一个扩展方法来做到这一点:

public static string GetDescription(this Enum enumValue) 
    { 
     //Look for DescriptionAttributes on the enum field 
     object[] attr = enumValue.GetType().GetField(enumValue.ToString()) 
      .GetCustomAttributes(typeof (DescriptionAttribute), false); 

     if (attr.Length > 0) // a DescriptionAttribute exists; use it 
      return ((DescriptionAttribute) attr[0]).Description; 

     //The above code is all you need if you always use DescriptionAttributes; 
     //If you don't, the below code will semi-intelligently 
     //"humanize" an UpperCamelCased Enum identifier 
     string result = enumValue.ToString(); 

     //"FooBar" -> "Foo Bar" 
     result = Regex.Replace(result, @"([a-z])([A-Z])", "$1 $2"); 

     //"Foo123" -> "Foo 123" 
     result = Regex.Replace(result, @"([A-Za-z])([0-9])", "$1 $2"); 

     //"123Foo" -> "123 Foo" 
     result = Regex.Replace(result, @"([0-9])([A-Za-z])", "$1 $2"); 

     //"FOOBar" -> "FOO Bar" 
     result = Regex.Replace(result, @"(?<!^)(?<!)([A-Z][a-z])", " $1"); 

     return result; 
    } 

用法:

var description = DataType.Alpha.GetDescription(); //"A" 

public enum TestEnums 
{ 
    IAmAComplexABCEnumValue, 
} 

//"I Am A Complex ABC Enum Value" 
var complexCamelCasedDescription = TestEnums.IAmAComplexABCEnumValue.GetDescription();