自定义ConfigurationElement属性验证失败

使用自己创建的ConfigurationElement时,一个字符串属性Name无法验证通过导致Element无法被构造,属性定义如下:

 
  
[ConfigurationProperty( " name " , IsRequired = true )] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\ " , MinLength = 1 , MaxLength = 60 )] public string Name { get { return ( string ) this [ " name " ]; } set { this [ " name " ] = value; } }

错误提示是"The value for the property 'name' is not valid. The error is: The string must be at least 1 characters long."当然事实上在config文件中定义的name值是满足条件的。

原因在于ConfigurationElement对象构造时,会首先用默认值来初始化各个属性,而这个默认值同样会接受validator的检验。这里的默认值是string.Empty,所以当然不满足条件了。

解决办法是为ConfigurationPropertyAttribute设置DefaultValue:

 
  
[ConfigurationProperty( " name " , DefaultValue = " unnamed " , IsRequired = true )] [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;'\"|\\ " , MinLength = 1 , MaxLength = 60 )] public string Name { get { return ( string ) this [ " name " ]; } set { this [ " name " ] = value; } }

同时由于这个属性是必须的(IsRequired = true),所以也不必担心默认值会真的被使用。

 

参考:

http://msdn.microsoft.com/en-us/library/system.configuration.configurationproperty(VS.85).aspx#1

 

此处指出了另一种可行的办法,而不必提供一个无用的默认值:

http://stackoverflow.com/questions/3744953/why-does-configurationvalidator-validate-the-default-value-of-a-configurationprop

 

另外附上一些关于Configuration的网页:

http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx

http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration2.aspx

Creating a Custom Configuration Section in C#

转载于:https://www.cnblogs.com/Gildor/archive/2011/01/13/1935150.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值