获取Serialization-attribute的值

时间:2013-12-16 10:09:35

标签: c# xml-serialization enumeration

我再次使用CSharp在XMLSerialzation上遇到问题。我有一个使用[System.Xml.Serialization.XmlEnumAttribute] -attribute序列化的枚举。

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

所以现在我想在我的应用程序中使用此属性的值。当我有枚举值时,有没有办法可以阅读它(例如“Wohnbaufläche”)?

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

这个方法getValueFromEnum应该如何检索枚举的字符串表示?

提前致谢

2 个答案:

答案 0 :(得分: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;

答案 1 :(得分: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);
    }

}