简体   繁体   English

Int会话变量增加?

[英]Int session variable to increment?

Can a session variable be an int ? 会话变量可以是int吗? I want to increment Session["PagesViewed"]+1; 我想增加Session["PagesViewed"]+1; every time a page is loaded. 每次加载页面。 I'm getting errors when trying to increment the session variable. 我在尝试增加会话变量时遇到错误。

if (Session["PagesViewed"].ToString() == "2")
{
     Session["PagesViewed"] = 0;
}
else
{
     Session["PagesViewed"]++;
}

You need to test to see if the Session variable exists before you can use it and assign to it. 您需要先测试Session变量是否存在,然后才能使用它并分配给它。

You can do increment as follows. 您可以按如下方式进行增量。

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

But, if the Session["PagesViewed"] does not exist, this will cause errors. 但是,如果Session["PagesViewed"]不存在,这将导致错误。 A quick null test before the increment should sort it out. 在增量之前进行快速null测试应该对其进行排序。

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

Session["PagesViewed"] will only return an Object - which is why your .ToString() call works. Session["PagesViewed"]只返回一个Object - 这就是你的.ToString()调用有效的原因。 You will need to cast this back to an int, increment it there, then put it back in the session. 您需要将其强制转换为int,将其递增,然后将其放回会话中。

Yes, it can be. 是的,它可以。 However, ++ only works when the compiler knows the object is an int. 但是, ++只有在编译器知道对象是int时才有效。 How does it know that some other part of your code doesn't sneakily do Session["PagesViewed"] = "Ha-ha"; 如何知道你的代码的其他部分不会偷偷地做Session["PagesViewed"] = "Ha-ha"; ?

You can effectively tell the compiler that you won't do something like that by casting: you'll get a runtime exception if the session variable isn't really an int. 您可以通过强制转换有效地告诉编译器您不会执行类似的操作:如果会话变量实际上不是int,您将获得运行时异常。

int pagesViewed = (int)Session["PagesViewed"];
if (pagesViewed == 2)
{
    pagesViewed = 0;
}
else
{
    pagesViewed++;
}
Session["PagesViewed"] = pagesViewed;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM