2013-12-16 91 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); 
    } 

}