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

在分析这个值时,是否需要忽略大小写?

推荐答案

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

.net相关问答推荐

图像 UriSource 和数据绑定

即时窗口中的动态导致Microsoft.CSharp.RuntimeBinder.Binder未定义或导入错误

如何使用 C# 中的代码更改网络设置(IP 地址、DNS、WINS、主机名)

log4net 与 TraceSource

如何明智地使用 StringBuilder?

如何在 WPF 应用程序中使用 App.config 文件?

为什么 ?: 会导致转换错误,而 if-else 不会?

如何在 C# 中将 HTML 转换为文本?

.NET - 实现捕获所有异常处理程序的最佳方法是什么

NuGetPackageImportStamp 有什么用?

我可以在没有两个查询的情况下通过布尔标准将 IEnumerable 一分为二吗?

.NET 的 String.Normalize 有什么作用?

如何从 .NET 读取 PEM RSA 私钥

C# 中的 F# List.map 类似功能?

在 .NET 中获取默认打印机的最佳方法是什么

更改 SqlConnection 超时

获取系统中已安装的应用程序

在 .NET 中乘以时间跨度

Roslyn 编译代码失败

如何将我的应用程序窗口置于最前面?