我正在創建一個自定義配置節(繼承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