Retrieve enum value based on XmlEnumAttribute name value

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

    @Dean, @Jason and @Camron, thank you for your solutions. Your solutions helped me in solving my problem, where, given an XmlEnumAttribute name, the actual enum value was needed.

    My variant is mentioned here.

    I am also including it here as as asked by one of our moderators:

    The actual problem was how to get Item10, when given a value of 10. Taking a cue from the solution cited by our above mentioned friends, I came up with the following method, which when passed a value contained in XmlEnumAttribute, would return the enum value:

    private static T GetEnumValueFromXmlAttrName(string attribVal)
    {
        T val = default(T);
    
        if (typeof(T).BaseType.FullName.Equals("System.Enum"))
        {
            FieldInfo[] fields = typeof(T).GetFields();
    
            foreach (FieldInfo field in fields)
            {
                object[] attribs = field.GetCustomAttributes(typeof(XmlEnumAttribute), false);
    
                foreach (object attr in attribs)
                {
                    if ((attr as XmlEnumAttribute).Name.Equals(attribVal))
                    {
                        val = (T)field.GetValue(null);
                        return val;
                    }
                }
            }
        }
        else
            throw new Exception("The supplied type is not an Enum.");
    
        return val;
    }
    

提交回复
热议问题