C# 在ConfigurationElement的属性getter/setter中测试值是一种好方法吗

C# 在ConfigurationElement的属性getter/setter中测试值是一种好方法吗,c#,app-config,configuration-management,C#,App Config,Configuration Management,下面是我为测试我的应用程序的app.config文件的值而编写的代码,我想知道这是否是一种好方法?我直接在MyProperty getter/setter中抛出ArgumentOutOfRangeException: internal sealed class ProcessingMyPropertyElement : ConfigurationElement { [ConfigurationProperty("myproperty", IsRequired = true)] p

下面是我为测试我的应用程序的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;
        }
    }
 }
内部密封类处理MyPropertyElement:ConfigurationElement
{
[ConfigurationProperty(“myproperty”,IsRequired=true)]
公共财产
{
得到
{
如果((int)this[“myproperty”]<0 | |(int)this[“myproperty”]>999)
抛出新ArgumentOutOfRangeException(“myproperty”);
返回(int)此[“myproperty”];
}
设置
{
如果(值<0 | |值>999)
抛出新ArgumentOutOfRangeException(“myproperty”);
此[“Recurivery”]=值;
}
}
}

设置值时,最好检查范围并在无效时引发异常

得到它后,我不会抛出异常。这样,有人可以通过手动编辑app.config使应用程序崩溃。在getter中,我会将该值限制在特定的范围内,并返回一个有效的结果

if ((int)this["myproperty"] < 0 )
{
     return 0;
}

if ((int)this["myproperty"] > 999 )
{
     return 999;
}

return (int)this["myproperty"]
if((int)this[“myproperty”]<0)
{
返回0;
}
如果((int)此[“myproperty”]>999)
{
返回999;
}
返回(int)此[“myproperty”]

听起来不错。在getter中,我将添加一个int.TryParse以检测配置文件中的非int值