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

前端 未结 3 1477
醉话见心
醉话见心 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条回答
  •  萌比男神i
    2021-02-03 17:46

    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 : 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))]
    public MeasurementUnits Unit { get { return (MeasurementUnits)this["unit"]; } }
    
    public enum MeasurementUnits
    {
            Pixel,
            Inches,
            Points,
            MM,
    }
    

提交回复
热议问题