我正在使用C#
我试图检查我的登录尝试是否不超过3,我的意思是以下条件
if (((int)Session["LoginAttempt"]) != 3)
{
}
Run Code Online (Sandbox Code Playgroud)
在登录失败的情况下,我正在执行如下增量:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
Run Code Online (Sandbox Code Playgroud)
但它给了我错误"对象引用未设置为对象的实例".
请指教!
Man*_*ngh 20
对不起大家,
我只是改变了整数转换代码
((int) Session["LoginAttempt"])
Run Code Online (Sandbox Code Playgroud)
至
Convert.ToInt32(Session["LoginAttempt"]) + 1;
Run Code Online (Sandbox Code Playgroud)
现在它对我来说很好,请提出任何问题.
谢谢!
试试魔法代码:
Session["LoginAttempt"] = ((int?)Session["LoginAttempt"] ?? 0) + 1;
Run Code Online (Sandbox Code Playgroud)
这会将会话变量Session["LoginAttempt"]转换为可空int(int可以是null),?? 0如果为null 则提供值0,因此计算成功.
该Session["LoginAttempt"]如果之前没有初始化可以为空.
您需要测试以查看Session变量是否存在,然后才能使用它并将其分配给它。
在这里,您正在增加:
Session["LoginAttempt"] = ((int) Session["LoginAttempt"]) + 1;
但是,如果Session["LoginAttempt"]不存在,这将解释您的错误。null在增加之前进行快速测试应该可以解决它。
if (Session["LoginAttempt"] != null)
Session["LoginAttempt"] = ((int)Session["LoginAttempt"]) + 1;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
55026 次 |
| 最近记录: |