之间的差异(静态int x和int x) [英] Defferent between (static int x and int x )

查看:372
本文介绍了之间的差异(静态int x和int x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的网页中,我输入了代码

in my web page , I put that code

static int x = 1;
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(x++);
}



我得到X值的增加

但没有静态就不会.



and I get increase in X value

but without static it doesn''t.

int x = 1;
protected void Page_Load(object sender, EventArgs e)
{
    Response.Write(x++);
}



它在哪里存储值?
它是如何工作的?
请.



where does it store the value?
how exactly does it work?
please.

推荐答案

不要依赖它.

static表示变量只有一个实例,并且所有类实例都共享它.在您的情况下,它是跨页面保留的,因为保存它的应用程序实例尚未在页面加载操作之间被服务器终止和卸载.这不能保证,也不能依靠.也可能会受到引用相同页面的其他用户的影响.

如果需要跨页面保留服务器值,则不要使用static-这将导致生产中产生不可预测的结果,这将非常非常难以跟踪和修复.使用会话变量 [
Don''t rely on it.

static means that there is a single instance of the variable and that it is shared by all class instances. In your case, it is being preserved across pages, because the instance of the application that holds it has not been terminated and unloaded by the server between page load operations. This is not guaranteed, and cannot be relied upon. It may also be affected by other users who reference the same pages.

If you need to preserve server values across pages, then do not use static - it will cause you unpredictable results in production which will be very, very difficult to track down and fix. Use Session variables[^] instead, as these are both designed to hold data across pages, and individual to each user.


这篇关于之间的差异(静态int x和int x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆