2010-10-05 49 views
1

我有一個枚舉,我需要通過傳遞 在「被保險人」才能參考。當我這樣做時,它說它不能被找到爲 實際的枚舉顯示爲InsuredOnly。有沒有反正我可以通過 正確的值,即「被保險人」而不是被保險人只有EnumMemberAttribute的幫助?

public enum EnumNames 
     { 
      Administrator, 
      [Description("Insured Only")] 
      InsuredOnly, 
     } 

回答

1

下面是應該做一個方便的泛型方法你想要什麼:

public T Parse<T>(string description) { 
    foreach (FieldInfo field in typeof(T).GetFields()) { 
     object[] attributes = field.GetCustomAttributes(typeof(DescriptionAttribute), false); 
     if ((attributes.Length > 0) 
      && ((DescriptionAttribute)attributes[0]).Description.Equals(description) 
     ) return (T)field.GetRawConstantValue(); 
    } 

    // use default parsing logic if no match is found 
    return (T)Enum.Parse(typeof(T), description); 
} 

用例:

EnumNames value = Parse<EnumNames>("Insured Only"); 
2

「被保險人」是一個字符串,其中InsuredOnly是一個枚舉。即使你做的ToString(),這將是「InsuredOnly」

有幾個選擇這裏,僅舉幾例:
1)使用Dictionary<myenum,string>的價值觀
2)使用[Description("my description")]地圖( see this article
3)使用某種類型的令牌在枚舉,說下劃線,並使用string.Replace()

1

可以通過反射做到這一點(沒有做任何代碼廣泛的測試,但希望你這個想法):

private static T GetEnumValue<T>(string description) 
{ 
    // get all public static fields from the enum type 
    FieldInfo[] ms = typeof(T).GetFields(BindingFlags.Public | BindingFlags.Static); 
    foreach (FieldInfo field in ms) 
    { 
     // pull out the DescriptionAttribute (if any) from the field 
     var descriptionAttribute = field 
      .GetCustomAttributes(typeof(DescriptionAttribute), true) 
      .FirstOrDefault(); 
     // Check if there was a DescriptionAttribute, and if the 
     // description matches 
     if (descriptionAttribute != null 
      && (descriptionAttribute as DescriptionAttribute).Description 
        .Equals(description, StringComparison.OrdinalIgnoreCase)) 
     { 
      // return the field value 
      return (T)field.GetValue(null); 
     } 
    } 
    return default(T); 
}