.net Custom Configuration How to case insensitive parse an enum ConfigurationProperty

前端 未结 3 1494
醉话见心
醉话见心 2021-02-03 16:58

One of the ConfigurationProperty I have in my ConfigurationSection is an ENUM. When .net parses this enum string value from the config file, an exception will be thrown if the c

3条回答
  •  一个人的身影
    2021-02-03 17:44

    MyEnum.TryParse() has an IgnoreCase parameter, set it true.

    http://msdn.microsoft.com/en-us/library/dd991317.aspx

    UPDATE: Defining the configuration section like this should work

    public class CustomConfigurationSection : ConfigurationSection
        {
          [ConfigurationProperty("myEnumProperty", DefaultValue = MyEnum.Item1, IsRequired = true)]
          public MyEnum SomeProperty
          {
            get
            {
              MyEnum tmp;
              return Enum.TryParse((string)this["myEnumProperty"],true,out tmp)?tmp:MyEnum.Item1;
            }
            set
            { this["myEnumProperty"] = value; }
          }
        }
    

提交回复
热议问题