C# .net 自定义配置如何不区分大小写解析枚举 ConfigurationProperty
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8922930/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.net Custom Configuration How to case insensitive parse an enum ConfigurationProperty
提问by Koda
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 case does not match exactly.
我的 ConfigurationSection 中的 ConfigurationProperty 之一是 ENUM。当 .net 从配置文件中解析此枚举字符串值时,如果大小写不完全匹配,则会抛出异常。
Is there away to ignore case when parsing this value?
解析此值时是否可以忽略大小写?
采纳答案by ziv
You can use ConfigurationConverterBase to make a custom configuration converter, see http://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx
您可以使用 ConfigurationConverterBase 制作自定义配置转换器,请参阅http://msdn.microsoft.com/en-us/library/system.configuration.configurationconverterbase.aspx
this will do the job:
这将完成这项工作:
public class CaseInsensitiveEnumConfigConverter<T> : 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<MeasurementUnits>))]
public MeasurementUnits Unit { get { return (MeasurementUnits)this["unit"]; } }
public enum MeasurementUnits
{
Pixel,
Inches,
Points,
MM,
}
回答by Marco
Try using this:
尝试使用这个:
Enum.Parse(enum_type, string_value, true);
Last param set to true tells to ignore string casing when parsing.
最后一个参数设置为 true 告诉在解析时忽略字符串大小写。
回答by tbt
MyEnum.TryParse()has an IgnoreCase parameter, set it true.
MyEnum.TryParse()有一个 IgnoreCase 参数,请将其设置为 true。
http://msdn.microsoft.com/en-us/library/dd991317.aspx
http://msdn.microsoft.com/en-us/library/dd991317.aspx
UPDATE: Defining the configuration section like this should work
更新:像这样定义配置部分应该可以工作
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; }
}
}

