Retrieve enum value based on XmlEnumAttribute name value

后端 未结 5 1940
北海茫月
北海茫月 2020-12-15 20:20

I need a Generic function to retrieve the name or value of an enum based on the XmlEnumAttribute \"Name\" property of the enum. For example I have the following enum define

5条回答
  •  感情败类
    2020-12-15 20:57

    Here's a variation that generates a dictionary from the enum, allowing you to potentially cache the reflection part of it should you need to use it a lot.

    /// 
    /// Generates a dictionary allowing you to get the csharp enum value
    /// from the string value in the matching XmlEnumAttribute.
    /// You need this to be able to dynamically set entries from a xsd:enumeration
    /// when you've used xsd.exe to generate a .cs from the xsd.
    /// https://msdn.microsoft.com/en-us/library/x6c1kb0s(v=vs.110).aspx
    /// 
    /// The xml enum type you want the mapping for
    /// Mapping dictionary from attribute values (key) to the actual enum values
    /// T must be an enum
    private static Dictionary GetEnumMap() where T : struct, IConvertible
    {
            if (!typeof(T).IsEnum)
            {
                    throw new ArgumentException("T must be an enum");
            }
            var members = typeof(T).GetMembers();
            var map = new Dictionary();
            foreach (var member in members)
            {
                    var enumAttrib = member.GetCustomAttributes(typeof(XmlEnumAttribute), false).FirstOrDefault() as XmlEnumAttribute;
                    if (enumAttrib == null)
                    {
                            continue;
                    }
                    var xmlEnumValue = enumAttrib.Name;
                    var enumVal = ((FieldInfo)member).GetRawConstantValue();
                    map.Add(xmlEnumValue, (T)enumVal);
            }
            return map;
    }
    

    usage:

    var map = GetEnumMap();
    return map["02"]; // returns Currency.EUR
    

提交回复
热议问题