hwi*_*ers 12 .net c# system.configuration
假设我有一个看起来像这样的配置属性.请注意,没有默认值.
[ConfigurationProperty("x", IsRequired = true)]
[StringValidator(MinLength = 1)]
public string X
{
    get { return (string)this["x"]; }
    set { this["x"] = value; }
}
现在我添加我的部分如下:
<mySection x="123" />
我会收到这个错误:
属性"x"的值无效.错误是:字符串长度必须至少为1个字符.
如果我更改配置属性以包含这样的默认值,它可以工作:
[ConfigurationProperty("x", DefaultValue="abc", IsRequired = true)]
[StringValidator(MinLength = 1)]
public string X
{
    get { return (string)this["x"]; }
    set { this["x"] = value; }
}
这意味着即使IsRequired为true,验证器也会验证默认值.这也意味着我必须在我的所有属性上包含一个虚拟默认值来传递验证,即使它们实际上不会被使用.
这只是糟糕的设计还是有这种行为的正当理由?
我以前遇到过这个问题.这是有正当理由但我不记得细节.
我不记得这是否有效,但您可以尝试在构造函数中声明属性,其中null是默认值.
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
编辑
我刚试过以前的代码,它按照我的预期进行.我之前的代码没有编译,因为我错过了一个构造函数属性,所以我修复了它.
| 归档时间: | 
 | 
| 查看次数: | 3758 次 | 
| 最近记录: |