代码之家  ›  专栏  ›  技术社区  ›  hwiechers

为什么ConfigurationValidator即使IsRequired为true也要验证ConfigurationProperty的默认值?

  •  12
  • hwiechers  · 技术社区  · 14 年前

    假设我有一个像这样的配置属性。请注意,没有默认值。

    [ConfigurationProperty("x", IsRequired = true)]
    [StringValidator(MinLength = 1)]
    public string X
    {
        get { return (string)this["x"]; }
        set { this["x"] = value; }
    }
    

    现在我添加如下部分:

    <mySection x="123" />
    

    属性“x”的值无效

    如果我更改configuration属性以包含如下默认值,它就会起作用:

    [ConfigurationProperty("x", DefaultValue="abc", IsRequired = true)]
    [StringValidator(MinLength = 1)]
    public string X
    {
        get { return (string)this["x"]; }
        set { this["x"] = value; }
    }
    

    这意味着即使IsRequired为true,验证器也会验证默认值。这也意味着我必须在所有属性上包含一个虚拟的默认值才能通过验证,即使它们实际上不会被使用。

    这仅仅是一个糟糕的设计,还是有一个合理的原因导致这种行为?

    3 回复  |  直到 14 年前
        1
  •  7
  •   Community CDub    9 年前

    我以前有过这个问题。有一个合理的理由,但我不记得细节。

    public class CustomConfigurationSection : ConfigurationSection
    {
        public CustomConfigurationSection()
        {
            Properties.Add(new ConfigurationProperty(
                "x",
                typeof(string),
                null,
                null,
                new StringValidator(1),
                ConfigurationPropertyOptions.IsRequired));
        }
    
    
        public string X
        {
            get { return (string)this["x"]; }
            set { this["x"] = value; }
        }
    }
    

    这与使用默认值和验证器有关,但是需要使用默认值。 http://msdn.microsoft.com/en-us/library/system.configuration.configurationproperty(VS.85).aspx#1

    编辑

    我刚刚尝试了前面的代码,它做了我所期望的。我以前的代码没有编译,因为我遗漏了一个构造函数属性,所以我已经修复了它。

        2
  •  3
  •   Michiel van Oosterhout    13 年前

    IsRequired=true 没有引发异常。换句话说, IsRequired 仅适用于从XML反序列化属性的情况。

    然而, DefaultValue 在本例中应用,就像从XML反序列化属性时一样(任何 ConfigurationValidatorAttribute ).

    如果您在单元测试中使用配置部分,这是有意义的。这真的很好,A)有一个声明性的默认值时,构造节和B)有默认值验证。

        3
  •  0
  •   Siva Gopal    14 年前

    据我所知,这种行为是非常必要的。

    由于配置是任何应用程序的核心领域之一,并且假设没有为应用程序关键属性提供任何值,那么整个应用程序可能会导致一些不需要的行为(可能是崩溃、不确定的资源利用率等)。我认为这就是原因,大多数.Net内置的配置属性,如会话超时等,都被设置为默认值,即使用户没有指定值,它们也会被应用。

        4
  •  0
  •   Yet Another Code Maker    4 年前

    如前所述,这无助于在不必为属性指定默认值的情况下获得验证,这会使ConfigurationPropertyAttribute的IsRequired属性变得无用。