2012-05-02 15 views
16

he el siguiente códigoUso EnumMemberAttribute y haciendo la conversión de series automáticas

[DataContract] 
public enum StatusType 
{ 
    [EnumMember(Value = "A")] 
    All, 
    [EnumMember(Value = "I")] 
    InProcess, 
    [EnumMember(Value = "C")] 
    Complete, 
} 

me gustaría hacer lo siguiente:

var s = "C"; 
StatusType status = SerializerHelper.ToEnum<StatusType>(s); //status is now StatusType.Complete 
string newString = SerializerHelper.ToEnumString<StatusType>(status); //newString is now "C" 

que he hecho la segunda parte utilizando DataContractSerializer (véase el código a continuación), pero parece mucho trabajo.

¿Me falta algo obvio? Ideas? Gracias.

public static string ToEnumString<T>(T type) 
    { 
     string s; 
     using (var ms = new MemoryStream()) 
     { 
      var ser = new DataContractSerializer(typeof(T)); 
      ser.WriteObject(ms, type); 
      ms.Position = 0; 
      var sr = new StreamReader(ms); 
      s = sr.ReadToEnd(); 
     } 
     using (var xml = new XmlTextReader(s, XmlNodeType.Element, null)) 
     { 
      xml.MoveToContent(); 
      xml.Read(); 
      return xml.Value; 
     } 
    } 
+1

tengo como esta opción, ya que se extiende Enum: http: // stackoverflow. com/a/4367868/1243316 –

Respuesta

26

Aquí es mi propuesta - que debe darle la idea sobre cómo hacer esto (revisar también Getting attributes of Enum's value):

public static string ToEnumString<T>(T type) 
{ 
    var enumType = typeof (T); 
    var name = Enum.GetName(enumType, type); 
    var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single(); 
    return enumMemberAttribute.Value; 
} 

public static T ToEnum<T>(string str) 
{ 
    var enumType = typeof(T); 
    foreach (var name in Enum.GetNames(enumType)) 
    { 
     var enumMemberAttribute = ((EnumMemberAttribute[])enumType.GetField(name).GetCustomAttributes(typeof(EnumMemberAttribute), true)).Single(); 
     if (enumMemberAttribute.Value == str) return (T)Enum.Parse(enumType, name); 
    } 
    //throw exception or whatever handling you want or 
    return default(T); 
} 
3

Puede utilizar la reflexión para obtener el valor de la EnumMemberAttribute.

public static string ToEnumString<T>(T instance) 
{ 
    if (!typeof(T).IsEnum) 
     throw new ArgumentException("instance", "Must be enum type"); 
    string enumString = instance.ToString(); 
    var field = typeof(T).GetField(enumString); 
    if (field != null) // instance can be a number that was cast to T, instead of a named value, or could be a combination of flags instead of a single value 
    { 
     var attr = (EnumMemberAttribute)field.GetCustomAttributes(typeof(EnumMemberAttribute), false).SingleOrDefault(); 
     if (attr != null) // if there's no EnumMember attr, use the default value 
      enumString = attr.Value; 
    } 
    return enumString; 
} 

Dependiendo de cómo sus obras ToEnum, es posible que desee utilizar este tipo de enfoque también allí. Además, el tipo puede inferirse al llamar al ToEnumString, p. SerializerHelper.ToEnumString(status);

Cuestiones relacionadas