Używanie EnumMemberAttribute i wykonywanie automatycznych konwersji łańcuchów
Mam następujący kod
<code>[DataContract] public enum StatusType { [EnumMember(Value = "A")] All, [EnumMember(Value = "I")] InProcess, [EnumMember(Value = "C")] Complete, } </code>
Chciałbym wykonać następujące czynności:
<code> var s = "C"; StatusType status = SerializerHelper.ToEnum<StatusType>(s); //status is now StatusType.Complete string newString = SerializerHelper.ToEnumString<StatusType>(status); //newString is now "C" </code>
Zrobiłem drugą część za pomocą DataContractSerializer (zobacz kod poniżej), ale wygląda na to, że jest dużo pracy.
Czy brakuje mi czegoś oczywistego? Pomysły? Dzięki.
<code> 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; } } </code>