在ConfigurationElement的属性getter / setter中测试值是一个好方法吗?
本文关键字:一个 方法 属性 ConfigurationElement getter 测试 setter | 更新日期: 2023-09-27 18:18:17
这是我写的测试我的应用程序的app.config文件的值,我想知道如果这是一个好方法?我直接在MyProperty getter/setter中抛出ArgumentOutOfRangeException:
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"]