我正在创建一个自定义配置节(继承System.Configuration.ConfigurationSection),并且我想知道是否必须对可为Nullable int的ConfigurationProperty进行值验证。即,我必须这样做:我必须对类型为Nullable <int>的房产进行验证吗?
[ConfigurationProperty("NullableInt", IsRequired = true)]
public int? NullableInt
{
get
{
return String.IsNullOrEmpty(Convert.ToString(this["NullableInt"]))
? (int?) null
: Convert.ToInt32(this["NullableInt"]);
}
set
{
this["NullableInt"] = value.HasValue ? Convert.ToString(value) : "";
}
}
或者,我可以做这样的事情:
[ConfigurationProperty("NullableInt", IsRequired = true)]
public int? NullableInt
{
get{ return Convert.ToInt32(this["NullableInt"]); }
set{ this["NullableInt"] = Convert.ToString(value); }
}
还是有更好的办法全在一起吗?
在此先感谢。
在这种情况下,你会使用Convert.ToInt32()Int32.Parse()吗?我在想,String.IsNullOrEmpty()会捕获Int32.Parse()会失败的任何场景,难道不会? – 2009-08-04 16:11:59
要么工作..它真的取决于你的最终目标是什么,但不要忘记,当表达式不是数字的时候转换器会抛出异常(即'a123bcd')所以,也许try catch将是有序的。 。和使用Int32.Parse()来简化事情.. – 2009-08-04 16:30:49