我正在使用C#。
我正在尝试检查我的登录尝试次数是否超过3次,我的意思是使用以下条件:
if (((int)Session["LoginAttempt"]) != 3)
{
}
在登录失败的情况下,我执行以下递增操作:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
但是它给了我这个错误:"对象引用未设置为对象的实例。"
请提供建议!
我正在使用C#。
我正在尝试检查我的登录尝试次数是否超过3次,我的意思是使用以下条件:
if (((int)Session["LoginAttempt"]) != 3)
{
}
在登录失败的情况下,我执行以下递增操作:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
但是它给了我这个错误:"对象引用未设置为对象的实例。"
请提供建议!
非常抱歉,大家好:
我刚刚修改了将整数转换的代码,从
((int) Session["LoginAttempt"])
Convert.ToInt32(Session["LoginAttempt"]) + 1;
现在它对我来说运行良好,请在任何问题的情况下提供建议。
谢谢!
Session["LoginAttempt"] = ((int?)Session["LoginAttempt"] ?? 0) + 1;
这将把会话变量Session["LoginAttempt"]
转换为可空的int
(一个可以是null
的int
),?? 0
如果它是null
则提供值0,因此计算成功。
如果Session["LoginAttempt"]
在使用前未初始化,则可能为null。
在使用和赋值Session
变量之前,您需要测试其是否存在。
这里进行了递增操作:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
但是,如果Session["LoginAttempt"]
不存在,这将解释您的错误。在递增之前进行快速的null
测试应该可以解决它。
if (Session["LoginAttempt"] != null)
Session["LoginAttempt"] = ((int)Session["LoginAttempt"]) + 1;
protected int LoginAttempt
{
get
{
if (Session["LoginAttempt"] == null)
{
Session["LoginAttempt"] = 1;
}
return Convert.ToInt32(Session["LoginAttempt"].ToString());
}
set
{
Session["LoginAttempt"] = value;
}
}
这样可以使函数主体更易读:
if (LoginAttempt < 3)
{
}
如果您之前没有初始化它,第一次尝试设置它时会执行此操作。请改为尝试以下操作:
if (Session["LoginAttempt"] == null)
Session["LoginAttempt"] = 1;
else
((int)Session["LoginAttempt"]) += 1;
将你的非平凡代码分成几个部分:
int sessionLogicAttempt = (int)Session["LoginAttempt"];
int someValue = sessionLogicAttempt + 1;
Session["LoginAttempt"] = someValue;
//read
object attemptObj = Session["LoginAttempt"]
int attempt = 0;
if (attemptObj != null) attempt = (int)attemptObj ;
////write
Session["LoginAttempt"] = attempt++;
尝试确保不要对可能为 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
}