Retrieve enum value based on XmlEnumAttribute name value

后端 未结 5 1927
北海茫月
北海茫月 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 21:03

    I do something similar with custom attributes and I use this method to get the EnumValue based on the Attribute Value. GetStringValue is my custom method, similar to your example above.

    public static class Enums 
    { 
        public static T GetCode(string value) 
        { 
            foreach (object o in System.Enum.GetValues(typeof(T))) 
            { 
                if (((Enum)o).GetStringValue().Equals(value, StringComparison.OrdinalIgnoreCase))
                    return (T)o; 
            } 
            throw new ArgumentException("No code exists for type " + typeof(T).ToString() + " corresponding to value of " + value); 
        } 
    }  
    

    For the whole process I use check this post and the answers: Extending Enums, Overkill?

    Sorry this is in C#, just realized you were using VB.NET above.

提交回复
热议问题