2012-01-19 11 views
22

私のConfigurationSectionにあるConfigurationPropertyの1つはENUMです。 .netがこのenum文字列値を設定ファイルから解析するとき、大文字小文字が正確に一致しない場合は例外がスローされます。.netカスタム設定大文字小文字を区別しない大文字と小文字を区別するEnum ConfigurationProperty

この値を解析するときに大文字小文字を無視することはありませんか?

+4

'Enum.Parse'は、ケースを無視するように指示するブール値を受け入れます。 – Joey

+2

@teddyこれは、enumメンバーがすべて大文字である場合にのみ役立ちます。 –

+0

はいEnum.Parseにignorecaseフラグがあることを認識しています。しかし、.netはConfigurationPropertyAttributeを使用すると自動的にこのConfigurationPropertyを解析します。 – Koda

答えて

25

を動作するはずの定義:

public class CaseInsensitiveEnumConfigConverter<T> : ConfigurationConverterBase 
    { 
     public override object ConvertFrom(
     ITypeDescriptorContext ctx, CultureInfo ci, object data) 
     { 
      return Enum.Parse(typeof(T), (string)data, true); 
     } 
    } 
あなたの財産上の10

、その後:

[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

は、この使用してみてください:trueに

Enum.Parse(enum_type, string_value, true); 

最後のparamセットを解析する際に、文字列のケースを無視するように指示します。

+2

これは受け入れられる回答である必要があります。 – starbeamrainbowlabs

+0

間違いなく、これは正しい答えです! –

+4

元の質問に対するKodaのコメントを読んでください。これは、大文字と小文字が区別されるモードで自動的に解析されるConfigurationPropertyAttributeを使用しています。 Enum.Parseは直接使用されません。受け入れられた答え(ConfigurationConvertorBaseから継承)が正しい答えです。 –

6

MyEnum.TryParse()にはIgnoreCaseパラメータがあります。これをtrueに設定します。

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

UPDATE: あなたはhttp://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx

これは、仕事をする参照、カスタム構成コンバータを作るためにConfigurationConverterBaseを使用することができます。このような構成セクションが

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

関連する問題