c#-.net自定义配置如何不区分大小写解析枚举ConfigurationProperty

我在ConfigurationSection中拥有的ConfigurationProperty之一是ENUM。 当.net从配置文件解析此枚举字符串值时,如果大小写不完全匹配,则将引发异常。

解析此值时是否有忽略大小写的地方?

Koda asked 2019-11-18T04:00:21Z
3个解决方案
200 votes

试试这个:

Enum.Parse(enum_type, string_value, true);

最后一个参数设置为true表示在解析时忽略字符串大小写。

Marco answered 2019-11-18T04:01:22Z
37 votes

您可以使用ConfigurationConverterBase来创建自定义配置转换器,请参阅[http://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx]

这将完成工作:

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

然后在您的媒体资源上:

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

public enum MeasurementUnits
{
        Pixel,
        Inches,
        Points,
        MM,
}
ziv answered 2019-11-18T04:00:56Z
19 votes

MyEnum.TryParse()具有IgnoreCase参数,将其设置为true。

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

更新:像这样定义配置部分应该可以

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; }
      }
    }
tbt answered 2019-11-18T04:01:58Z
translate from https://stackoverflow.com:/questions/8922930/net-custom-configuration-how-to-case-insensitive-parse-an-enum-configurationpro