ConfigurationSectionにあるConfigurationPropertyの1つはENUMです。.netが構成ファイルからこの列挙型文字列値を解析するときに、大文字と小文字が完全に一致しない場合は例外がスローされます。
この値を解析するときに大文字と小文字を無視する方法はありますか?
ConfigurationSectionにあるConfigurationPropertyの1つはENUMです。.netが構成ファイルからこの列挙型文字列値を解析するときに、大文字と小文字が完全に一致しない場合は例外がスローされます。
この値を解析するときに大文字と小文字を無視する方法はありますか?
これを使用してみてください:
Enum.Parse(enum_type, string_value, true);
最後のパラメータをtrueに設定すると、解析時に文字列の大文字と小文字を無視するように指示されます。
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,
}
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; }
}
}