Retrieve enum value based on XmlEnumAttribute name value

后端 未结 5 1954
北海茫月
北海茫月 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:58

    A requirement to solve this exact same problem led me to this question and answer. As I develop in VB.NET, I rewrote CkH's solution into VB and modified it to use your GetXmlAttrNameFromEnumValue function.

    Public Shared Function GetCode(Of T)(ByVal value As String) As T
        For Each o As Object In System.Enum.GetValues(GetType(T))
            Dim enumValue As T = CType(o, T)
            If GetXmlAttrNameFromEnumValue(Of T)(enumValue).Equals(value, StringComparison.OrdinalIgnoreCase) Then
                Return CType(o, T)
            End If
        Next
    
        Throw New ArgumentException("No code exists for type " + GetType(T).ToString() + " corresponding to value of " + value)
    End Function
    

    C# Version:

    public static string GetXmlAttrNameFromEnumValue(T pEnumVal)
    {
        // http://stackoverflow.com/q/3047125/194717
        Type type = pEnumVal.GetType();
        FieldInfo info = type.GetField(Enum.GetName(typeof(T), pEnumVal));
        XmlEnumAttribute att = (XmlEnumAttribute)info.GetCustomAttributes(typeof(XmlEnumAttribute), false)[0];
        //If there is an xmlattribute defined, return the name
    
        return att.Name;
    }
    public static T GetCode(string value)
    {
        // http://stackoverflow.com/a/3073272/194717
        foreach (object o in System.Enum.GetValues(typeof(T)))
        {
            T enumValue = (T)o;
            if (GetXmlAttrNameFromEnumValue(enumValue).Equals(value, StringComparison.OrdinalIgnoreCase))
            {
                return (T)o;
            }
        }
    
        throw new ArgumentException("No XmlEnumAttribute code exists for type " + typeof(T).ToString() + " corresponding to value of " + value);
    }
    

提交回复
热议问题