自定义ConfigurationElement中ConfigurationProperty中的意外RegexStringValidator失败

Jed*_*Jed 7 c# regex configuration

我正在编写自己的自定义配置部分,并在ConfigurationElement中定义了一个ConfigurationProperty,如下所示:

[ConfigurationProperty("startTime", IsRequired = false)]
[RegexStringValidator("\\d{2}:\\d{2}:\\d{2}")]
public string StartTime
{
    get
    {
        return (string) this["startTime"];
    }

    set
    {
        this["startTime"] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

我希望能够在我创建的ConfigurationElement的startTime属性中输入诸如"23:30:00"之类的值.但是,每当我尝试加载配置部分时,都会收到带有消息的ConfigurationErrorsException:

属性"startTime"的值无效.错误是:该值不符合验证正则表达式字符串'\ d {2}:\ d {2}:\ d {2}'.

我承认我总是在使用正则表达式,但是这个很简单,我写了一个测试来验证我的模式应该验证我期望的各种值:

var regex = new Regex(@"\d{2}:\d{2}:\d{2}", RegexOptions.Compiled);
var isSuccess = regex.Match("23:30:00").Success;
Run Code Online (Sandbox Code Playgroud)

isSuccess计算结果为True,因此我不太确定为什么会抛出ConfigurationErrorsException.

作为参考,这是我的App.config文件中的配置部分:

<windowsServiceConfiguration>
  <schedule startTime = "23:00:00" />
</windowsServiceConfiguration>
Run Code Online (Sandbox Code Playgroud)

任何关于为什么我不能让RegexStringValidator工作的帮助将不胜感激.谢谢.

小智 16

尝试定义将通过验证的默认值:

[ConfigurationProperty("startTime", IsRequired = false, DefaultValue = "00:00:00")]
[RegexStringValidator(@"\d{2}:\d{2}:\d{2}")]
public string StartTime
{
    get 
    {
        return (string) this["startTime"];
    }

    set
    {
        this["startTime"] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)