我試圖賦予null的變量IdSubCategory
如果會話變量Session["SubCategory"]
是空分配null以十進制MVC 3
爲什麼下面不工作?
decimal tmpvalue2;
decimal? IdSubCategory = null;
if (decimal.TryParse((string)Session["SubCategory"], out tmpvalue2))
IdSubCategory = tmpvalue2;
我試圖賦予null的變量IdSubCategory
如果會話變量Session["SubCategory"]
是空分配null以十進制MVC 3
爲什麼下面不工作?
decimal tmpvalue2;
decimal? IdSubCategory = null;
if (decimal.TryParse((string)Session["SubCategory"], out tmpvalue2))
IdSubCategory = tmpvalue2;
我通常將我的會話變量包裝在屬性中。
protected decimal? IdSubCategory
{
get
{
if (Session["SubCategory"] == null)
return null;
else
return decimal.Parse(Session["SubCategory"].ToString());
}
set
{
Session["SubCategory"] = value;
}
}
decimal.TryParse需要一個字符串轉換,但如果Session["SubCategory"]
爲null,則你的代碼行正試圖施放一個空字符串將錯誤
這一個方法:if (decimal.TryParse((string)Session["SubCategory"], out tmpvalue2))
爲了解決它,請先檢查,如果Session["SubCategory"]
不爲空,然後嘗試做十進制。嘗試Parse
什麼不起作用?你在Session["SubCategory"]
存儲什麼?
這些測試存儲串表示在會話對象的ID時通過:
[Test] public void GivenWhenIntegerString_WhenTryParse_ThenValidInteger()
{
Dictionary<string, Object> fakeSession = new Dictionary<string, object>();
fakeSession["SubCategory"] = "5";
decimal tmp;
decimal? IdSubCategory = null;
if (decimal.TryParse((string)fakeSession["SubCategory"], out tmp))
IdSubCategory = tmp;
Assert.That(IdSubCategory, Is.EqualTo(5d));
}
[Test] public void GivenWhenNull_WhenTryParse_ThenNull()
{
Dictionary<string, Object> fakeSession = new Dictionary<string, object>();
fakeSession["SubCategory"] = null;
decimal tmp;
decimal? IdSubCategory = null;
if (decimal.TryParse((string)fakeSession["SubCategory"], out tmp))
IdSubCategory = tmp;
Assert.That(IdSubCategory, Is.EqualTo(null));
}
當在Session["SubCategory"]
[Test]
public void GivenWhenInteger_WhenTryParse_ThenValidInteger()
{
Dictionary<string, Object> fakeSession = new Dictionary<string, object>();
fakeSession["SubCategory"] = 5;
decimal tmp;
decimal? IdSubCategory = null;
if (decimal.TryParse((string)fakeSession["SubCategory"], out tmp))
IdSubCategory = tmp;
Assert.That(IdSubCategory, Is.EqualTo(5d));
}
存儲int
或decimal
在這種情況下該測試失敗,這將修復它:
decimal tmp;
decimal? IdSubCategory = null;
if (Session["SubCategory"] != null &&
decimal.TryParse(Session["SubCategory"].ToString(), out tmp))
IdSubCategory = tmp;
給我們更詳細的信息d關於問題的信息以及爲什麼你不認爲它有效。 – 2012-07-11 17:17:53
你會得到什麼? – 2012-07-11 17:18:11