-2

IdSubCategory如果会话变量Session["SubCategory"]为 null ,我正在尝试将 null 分配给变量

为什么以下不起作用?

decimal tmpvalue2;
decimal? IdSubCategory = null;    
if (decimal.TryParse((string)Session["SubCategory"], out tmpvalue2))
    IdSubCategory = tmpvalue2;
4

3 回答 3

2

我通常将会话变量包装在一个属性中。

    protected decimal? IdSubCategory
    {
        get
        {
            if (Session["SubCategory"] == null)
                return null;
            else
                return decimal.Parse(Session["SubCategory"].ToString());
        }
        set
        {
            Session["SubCategory"] = value;
        }
    }
于 2012-07-11T17:35:02.433 回答
0

方法 decimal.TryParse 需要一个要转换的字符串,但如果Session["SubCategory"]为 null,那么您的代码行正在尝试将 null 转换为字符串,这将出错

这个 :if (decimal.TryParse((string)Session["SubCategory"], out tmpvalue2))

为了修复它,请先检查是否Session["SubCategory"]不为空,然后尝试执行小数。TryParse

于 2012-07-11T18:06:32.513 回答
0

什么不工作?你在存储什么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));            
}

当您将intor存储decimalSession["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));
}

在这种情况下,这将解决它:

decimal tmp;
decimal? IdSubCategory = null;
if (Session["SubCategory"] != null &&
    decimal.TryParse(Session["SubCategory"].ToString(), out tmp))
  IdSubCategory = tmp;
于 2012-07-11T18:24:56.150 回答