它是一个很好的方式来测试ConfigurationElement属性获取/设置值
问题描述:
这是我写的测试我的应用程序的app.config文件的值,我想知道这是一个好方法吗?我直接在myProperty的getter/setter方法抛出一个ArgumentOutOfRangeException:它是一个很好的方式来测试ConfigurationElement属性获取/设置值
internal sealed class ProcessingMyPropertyElement : ConfigurationElement
{
[ConfigurationProperty("myproperty", IsRequired = true)]
public int MyProperty
{
get
{
if ((int)this["myproperty"] < 0 || (int)this["myproperty"] > 999)
throw new ArgumentOutOfRangeException("myproperty");
return (int)this["myproperty"];
}
set
{
if (value < 0 || value > 999)
throw new ArgumentOutOfRangeException("myproperty");
this["recurEvery"] = value;
}
}
}
答
当设定值是检查的范围,并抛出一个异常时,这是无效的一个好主意。
在得到它的时候,我不会抛出异常。这样,有人可以通过手动编辑app.config来使应用程序崩溃。在你的getter中,我将限制值到特定的范围并返回一个有效的结果。
if ((int)this["myproperty"] < 0)
{
return 0;
}
if ((int)this["myproperty"] > 999)
{
return 999;
}
return (int)this["myproperty"]
听起来很好。在getter中,我会添加一个int.TryParse以检测配置文件中的非int值 – 2011-12-20 09:50:18