Get element of an enum by sending XmlEnumAttribute c#?

后端 未结 2 1378
感动是毒
感动是毒 2021-01-25 02:38

I normaly dont have to ask questions because most of the times I find what I need on internet, but now i haven´t find a way to get this:

Imagine that I have like 50000

2条回答
  •  耶瑟儿~
    2021-01-25 03:29

    Thanks dbc the first method works perfectly for what i need to do, :) i really appreciate your help, i created this class:

    public static partial class XmlEnumExtensions
    {
        public static Nullable FromReflectedXmlValue(this string xml) where TEnum : struct, IConvertible, IFormattable
        {
            try
            {
                var obj = (from field in typeof(TEnum).GetFields(BindingFlags.Public | BindingFlags.Static)
                           from attr in field.GetCustomAttributes()
                           where attr != null && attr.Name == xml
                           select field.GetValue(null)).SingleOrDefault();
                if (obj != null)
                    return (TEnum)obj;
                 // OK, maybe there is no XmlEnumAttribute override so match on the name.
                return (TEnum)Enum.Parse(typeof(TEnum), xml, false);
    
            }
            catch (ArgumentException ex)
            {
                throw new ApplicationException("Error: " + ex.Message);
            }
        }
    }
    

    And then I just call the method FromReflectedXmlValue like this:

    var obj4 = XmlEnumExtensions.FromReflectedXmlValue("theXmlAtributeValue");
    

提交回复
热议问题