Retrieve enum value based on XmlEnumAttribute name value

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

    Slightly modified from: http://www.wackylabs.net/2006/06/getting-the-xmlenumattribute-value-for-an-enum-field/

    public static string ToString2 (this Enum e) {
        // Get the Type of the enum
        Type t = e.GetType ();
    
        // Get the FieldInfo for the member field with the enums name
        FieldInfo info = t.GetField (e.ToString ("G"));
    
        // Check to see if the XmlEnumAttribute is defined on this field
        if (!info.IsDefined (typeof (XmlEnumAttribute), false)) {
            // If no XmlEnumAttribute then return the string version of the enum.
            return e.ToString ("G");
        }
    
        // Get the XmlEnumAttribute
        object[] o = info.GetCustomAttributes (typeof (XmlEnumAttribute), false);
        XmlEnumAttribute att = (XmlEnumAttribute)o[0];
        return att.Name;
    }
    

提交回复
热议问题