2012-01-19 24 views
22

我的ConfigurationSection中有一个ConfigurationProperty是ENUM。当.net从配置文件解析此枚举字符串值时,如果案例不完全匹配,则会引发异常。.net自定义配置如何区分大小写解析一个枚举ConfigurationProperty

解析此值时是否忽略大小写?

+4

'Enum.Parse'接受布尔告诉它忽略大小写。 – Joey

+2

@teddy只有在枚举成员全部大写时才会有帮助... –

+0

是的我知道Enum.Parse有一个ignorecase标志。但.net使用ConfigurationPropertyAttribute时会自动解析此ConfigurationProperty。 – Koda

回答

25

您可以使用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, 
} 
82

尝试使用这样的:

Enum.Parse(enum_type, string_value, true); 

末PARAM设置为true告诉解析时忽略字符串外壳。

+2

这应该是被接受的答案。 – starbeamrainbowlabs

+0

当然,这是正确的答案! –

+4

阅读Koda对原始问题的评论。它使用ConfigurationPropertyAttribute,在区分大小写模式下自动解析。 Enum.Parse不直接使用。接受的答案(从ConfigurationConvertorBase继承)是正确的答案。 –

6

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

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

UPDATE: 定义这样的配置部分应该工作

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

是的我知道Enum.Parse有一个ignorecase标志。但.net使用ConfigurationPropertyAttribute时会自动解析此ConfigurationProperty。 – Koda