如何在C#中将Session变量转换为整型?

13

我正在使用C#。

我正在尝试检查我的登录尝试次数是否超过3次,我的意思是使用以下条件:

if (((int)Session["LoginAttempt"]) != 3)
{
}

在登录失败的情况下,我执行以下递增操作:

Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;

但是它给了我这个错误:"对象引用未设置为对象的实例。"

请提供建议!

8个回答

23

非常抱歉,大家好:

我刚刚修改了将整数转换的代码,从

((int) Session["LoginAttempt"])
Convert.ToInt32(Session["LoginAttempt"]) + 1;

现在它对我来说运行良好,请在任何问题的情况下提供建议。

谢谢!


7
尝试使用神奇代码:
Session["LoginAttempt"] = ((int?)Session["LoginAttempt"] ?? 0) + 1;

这将把会话变量Session["LoginAttempt"]转换为可空的int(一个可以是nullint),?? 0如果它是null则提供值0,因此计算成功。

如果Session["LoginAttempt"]在使用前未初始化,则可能为null。


5

在使用和赋值Session变量之前,您需要测试其是否存在。

这里进行了递增操作:

Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;

但是,如果Session["LoginAttempt"]不存在,这将解释您的错误。在递增之前进行快速的null测试应该可以解决它。

if (Session["LoginAttempt"] != null)
    Session["LoginAttempt"] = ((int)Session["LoginAttempt"]) + 1;

4
为什么不将LoginAttempt值封装为属性并自动分配一个值:
protected int LoginAttempt
{
    get
    {
        if (Session["LoginAttempt"] == null)
        {
            Session["LoginAttempt"] = 1;
        }
        return Convert.ToInt32(Session["LoginAttempt"].ToString());
    }
    set
    {
        Session["LoginAttempt"] = value;
    }
}

这样可以使函数主体更易读:

if (LoginAttempt < 3)
{
}

1

如果您之前没有初始化它,第一次尝试设置它时会执行此操作。请改为尝试以下操作:

if (Session["LoginAttempt"] == null)
    Session["LoginAttempt"] = 1;
else
    ((int)Session["LoginAttempt"]) += 1;

0

将你的非平凡代码分成几个部分:

int sessionLogicAttempt = (int)Session["LoginAttempt"];
int someValue = sessionLogicAttempt + 1;
Session["LoginAttempt"] = someValue;

此外,添加断言以检查您所假定的值。

0
//read
object attemptObj = Session["LoginAttempt"]
int attempt = 0;
if (attemptObj != null) attempt = (int)attemptObj ;

////write
Session["LoginAttempt"] = attempt++;

0

尝试确保不要对可能为 null 值的内容进行强制转换。

int i = Session["val"] == null ? 0 : (int)Session["val"];

虽然这也可能会让你混乱,如果其他程序员使用了你的“val”会话并在那里放置了一个非整数值。

        int y = 0;
        if (int.TryParse(Session["val"] == null ? string.Empty : Session["val"].ToString(), out y))
        {
            // got your int value
        }
        else
        {
            // no int value in session val
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接