首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >c#如何预先验证所有ConfigurationElement属性?

c#如何预先验证所有ConfigurationElement属性?
EN

Stack Overflow用户
提问于 2017-10-28 00:35:41
回答 1查看 793关注 0票数 0

我有几个自定义配置元素(从ConfigurationElement派生的类),其中一些属性具有验证属性,其他属性是枚举类型。

问题是可以正确地创建配置对象,但只有在访问属性时才会抛出异常。(在这种情况下,字符串不会解析为任何已知的枚举值)。

我的问题是,在我继续之前,我能不能在程序启动时确保我的app.config文件中的任何自定义部分都没有问题?

谢谢,Radek

EN

回答 1

Stack Overflow用户

发布于 2017-11-02 01:32:04

给定包含enum的示例ConfigurationSection

代码语言:javascript
复制
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),则会抛出异常。

代码语言:javascript
复制
private void ValidateSection(object section)
{
    var context = new ValidationContext(section);
    Validator.ValidateObject(section, context);
}

不需要对象本身的验证属性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46979749

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档