我有几个自定义配置元素(从ConfigurationElement派生的类),其中一些属性具有验证属性,其他属性是枚举类型。
问题是可以正确地创建配置对象,但只有在访问属性时才会抛出异常。(在这种情况下,字符串不会解析为任何已知的枚举值)。
我的问题是,在我继续之前,我能不能在程序启动时确保我的app.config文件中的任何自定义部分都没有问题?
谢谢,Radek
发布于 2017-11-02 01:32:04
给定包含enum的示例ConfigurationSection
public class MyConfigurationSection : ConfigurationSection
{
[ConfigurationProperty(name: "myProperty")]
public TestEnum MyProperty =>
(TestEnum) Enum.Parse(typeof(TestEnum), Convert.ToString(base["myProperty"]));
}
public enum TestEnum
{
A = 1, B = 2
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="myConfigurationSection"
type="ValidatedConfigurationSection.MyConfigurationSection,
ValidatedConfigurationSection"/>
</configSections>
<myConfigurationSection myProperty="NoSuchValueInEnum"/>
</configuration>如果enum值无效(需要System.ComponentModel.DataAnnotations),则会抛出异常。
private void ValidateSection(object section)
{
var context = new ValidationContext(section);
Validator.ValidateObject(section, context);
}不需要对象本身的验证属性。
https://stackoverflow.com/questions/46979749
复制相似问题