2013-12-16 148 views
1

我再次遇到使用CSharp的XMLSerialzation問題。我有一個使用[System.Xml.Serialization.XmlEnumAttribute]屬性進行序列化的枚舉。獲取序列化屬性的值

public enum anEnum { 
    [System.Xml.Serialization.XmlEnumAttribute("Wohnbaufläche")] 
    Wohnbauflaeche, 
    ... 
} 

所以現在我想我的應用程序中使用該屬性的值。當我有枚舉值時,是否有方法可以讀取它(例如「Wohnbaufläche」)?

anEnum a = Wohnbauflaeche; 
string value = getValueFromEnum(a); 

該方法getValueFromEnum應該如何檢索字符串表示形式的枚舉?

在此先感謝

+0

我不認爲我明白你在問什麼。你想要一個Enum值的字符串表示嗎?試試'a.ToString()'。 –

+0

事實上,我需要一個字符串表示法,但它不那麼簡單,因爲enum-entry的名稱有時與我實際需要的值不同(請參閱Wohnbauflaeche反對Wohnbaufläche) – HimBromBeere

+0

這是另一回事。你需要解析字符串表示並檢查是否有任何等價的結構(例如'ae' <=>「ä」)。你需要什麼與序列化無關,而與枚舉幾乎沒有關係。你需要定義「同義詞」。 –

回答

3
var type = typeof(anEnum); 
    var memInfo = type.GetMember(anEnum.Wohnbauflaeche.ToString()); 
    var attributes = memInfo[0].GetCustomAttributes(typeof(XmlEnumAttribute), 
     false); 
    var value= ((XmlEnumAttribute)attributes[0]).Name; 
+0

工程就像一個魅力,非常感謝 – HimBromBeere

0

大量反射,基本上是:

var name = (from field in typeof(anEnum).GetFields(
    System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public) 
    where field.IsLiteral && (anEnum)field.GetValue(null) == a 
    let xa = (System.Xml.Serialization.XmlEnumAttribute) 
     Attribute.GetCustomAttribute(field, 
     typeof(System.Xml.Serialization.XmlEnumAttribute)) 
    where xa != null 
    select xa.Name).FirstOrDefault(); 

就個人而言,我會緩存他們都在一個Dictionary<anEnum,string> - 是這樣的:

anEnum a = anEnum.Wohnbauflaeche; 
string name = a.GetName(); 

使用:

public static class EnumHelper 
{ 
    public static string GetName<T>(this T value) where T : struct 
    { 
     string name; 
     return Cache<T>.names.TryGetValue(value, out name) ? name : null; 
    } 
    private static class Cache<T> 
    { 
     public static readonly Dictionary<T, string> names = (
        from field in typeof(T).GetFields(
         System.Reflection.BindingFlags.Static | 
         System.Reflection.BindingFlags.Public) 
        where field.IsLiteral 
        let value = (T)field.GetValue(null) 
        let xa = (System.Xml.Serialization.XmlEnumAttribute) 
         Attribute.GetCustomAttribute(field, 
         typeof(System.Xml.Serialization.XmlEnumAttribute)) 
        select new 
        { 
         value, 
         name = xa == null ? value.ToString() : xa.Name 
        } 
       ).ToDictionary(x => x.value, x => x.name); 
    } 

}