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

天大地大妈咪最大 提交于 2019-12-04 09:50:14

问题


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 case does not match exactly.

Is there away to ignore case when parsing this value?


回答1:


You can use ConfigurationConverterBase to make a custom configuration converter, see http://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx

this will do the job:

 public class CaseInsensitiveEnumConfigConverter<T> : ConfigurationConverterBase
    {
        public override object ConvertFrom(
        ITypeDescriptorContext ctx, CultureInfo ci, object data)
        {
            return Enum.Parse(typeof(T), (string)data, true);
        }
    }

and then on your property:

[ConfigurationProperty("unit", DefaultValue = MeasurementUnits.Pixel)]
[TypeConverter(typeof(CaseInsensitiveEnumConfigConverter<MeasurementUnits>))]
public MeasurementUnits Unit { get { return (MeasurementUnits)this["unit"]; } }

public enum MeasurementUnits
{
        Pixel,
        Inches,
        Points,
        MM,
}



回答2:


Try using this:

Enum.Parse(enum_type, string_value, true);

Last param set to true tells to ignore string casing when parsing.




回答3:


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; }
      }
    }


来源:https://stackoverflow.com/questions/8922930/net-custom-configuration-how-to-case-insensitive-parse-an-enum-configurationpro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!