C# 在类中初始化的变量随着页面加载而丢失其先前的值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10838426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:28:53  来源:igfitidea点击:

variable initialized in class loses its previous value with the page loading

c#asp.net

提问by Md. Arafat Al Mahmud

I've declared a String variable test with "hi". every time I click on Button1, I expect that test will be appended with its previous value. But I have noticed that it loses its previous value when the button is clicked and the page is reloaded. That is every time I click it, it has its text as "hihi". I expect "hihihihi" on the next click and so on. What's the problem here with the code below?

我已经用“hi”声明了一个字符串变量测试。每次单击 Button1 时,我都希望测试会附加其先前的值。但是我注意到当单击按钮并重新加载页面时,它会丢失以前的值。那是每次我点击它时,它的文字都是“hihi”。我希望下次点击时出现“hihihihi”等等。下面的代码有什么问题?

public partial class _Default : System.Web.UI.Page
{

    String test = "hi";

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        test += test;
        Button1.Text = test;
    }
}

采纳答案by aquinas

No, that's not the way asp.net works. If you need that behavior you should do this:

不,这不是 asp.net 的工作方式。如果您需要这种行为,您应该这样做:

public string test {
  get {
    return (string) ViewState["test"] ?? "hi";
  }
  set {
    ViewState["test"] = value;
  }
}

When ASP.NET sends a request to the server, a new version of your class is instantiated. If you need to get the state, you need to use ViewState (which is saved in a hidden field in the browser and sent with every request, and therefore state saved per page), or you can use SessionState which is a state saved per user. SessionState by default is saved in memory. So, if you restart IIS, this state will go away. Note that viewstate's state will NOT go away if you reset IIS (since it's being sent by the browser). You can also use the Cachewhich again, is saved in memory. This state is for allusers of your application. The same rules about resetting IIS apply. Finally, you could make your variable static. As I said, every time a request is made a new version of your class is instantiated. Of course, static variables are not instance variables, so the state of a static variable is saved across postbacks as well. The same rules about IIS reset apply to static variables as Cache and Session.

当 ASP.NET 向服务器发送请求时,您的类的新版本被实例化。如果需要获取状态,则需要使用 ViewState(保存在浏览器的隐藏字段中并随每个请求一起发送,因此每个页面保存状态),或者您可以使用 SessionState,它是每个用户保存的状态. SessionState 默认保存在内存中。因此,如果您重新启动 IIS,此状态将消失。请注意,如果您重置 IIS,viewstate 的状态不会消失(因为它是由浏览器发送的)。您也可以Cache再次使用它,保存在内存中。这种状态适用于所有人您的应用程序的用户。适用于重置 IIS 的相同规则。最后,您可以将变量设为静态。正如我所说,每次发出请求时,都会实例化一个新版本的类。当然,静态变量不是实例变量,因此静态变量的状态也可以跨回发保存。与 Cache 和 Session 一样,关于 IIS 重置的相同规则也适用于静态变量。

回答by Jupaol

This works, just try it

这有效,试试吧

// in the page load event
if(!this.IsPostBack)
   Button1.Text = test;

// in the Click event
this.Button1.Text += test;

The problem with your current code is that you are assigning an instance variableto the button text, since it is an instance variable it is being initialized every time you request the page with the same valuethat's why you always get hihionly and not hihihihihihihi

与您现有的代码的问题是,你分配一个实例变量的按钮上的文字,因为它是一个实例变量,它被初始化,您每次请求的页面具有相同价值的时间,这就是为什么你总能得到日冰,而不是hihihihihihihi

Every time you click the button, ASP.Net creates a new Page(), therefore the testmember will always be initialized like: test = "hi";.

每次单击按钮时,ASP.Net 都会创建一个new Page(),因此该test成员将始终初始化为:test = "hi";

回答by MethodMan

Thats because a button generates a POST BACK you could declare the variable as a Static Property or Create a Session["Test"] or add some code on the button click if IsPostback {}

那是因为按钮会生成 POST BACK,您可以将变量声明为静态属性或创建会话 ["Test"] 或在按钮点击时添加一些代码,如果 IsPostback {}

回答by Marc Gravell

A field only exists for the duration of a single request. If you want it to live between requests you'll have to use something like session-state, view-state, a cookie, or a HTML form / request value.

字段仅在单个请求的持续时间内存在。如果您希望它在请求之间存在,则必须使用诸如会话状态、视图状态、cookie 或 HTML 表单/请求值之类的东西。

In most "real" applications, you can't even guarantee that subsequent requests are being handled by the same physical machine.

在大多数“真实”应用程序中,您甚至无法保证后续请求由同一台物理机处理。

回答by AlwaysAProgrammer

Remember that on a postback the asp.net recreates the objects and reassigns the values. In your case the test variable gets recreated and gets assigned the value of 'hi'. You might want to store the variable in session and then append the value.

请记住,在回发时,asp.net 会重新创建对象并重新分配值。在您的情况下,测试变量被重新创建并被分配了“hi”的值。您可能希望将变量存储在会话中,然后附加该值。

回答by Kevin

Every time you visit a page, a new instance of the page is created with its own copy of your local variable. There are several ways you can persist values from one page view to the next, and they are all described here: ASP.NET State Management Overview

每次访问页面时,都会创建该页面的一个新实例,并使用它自己的本地变量副本。有多种方法可以将值从一个页面视图保存到下一个页面视图,它们都在此处进行了描述:ASP.NET 状态管理概述

回答by Matías Fidemraizer

String test = "hi";

This is a private, instance class field.

这是一个私有的实例类字段。

You need a static one if you want to achieve your goal.

如果你想实现你的目标,你需要一个静态的。

BTW, honestly, maybe you're looking to use a session item:

顺便说一句,老实说,也许您正在寻找使用会话项目:

HttpContext.Current.Session["test"] = "hi";

Doing this way you'll have a code like this in your event handler:

这样做你的事件处理程序中会有这样的代码:

string currentTestText = (string)HttpContext.Current.Session["test"];

currentTestText += currentTestText;
Button1.Text = currentTestText;

HttpContext.Current.Session["test"] = currentTestText;

回答by Claudio Redi

The problem with your code is that on every request your Pageinstance is recreated so testwon't keep the previous value since it belongs a new Pageinstance.

您的代码的问题在于,在每次请求时,您的Page实例都会重新创建,因此test不会保留以前的值,因为它属于一个新Page实例。

This is the flow:

这是流程:

Request 1 Start

请求 1 开始

Page is created -> test = "hi"

Request 1 Ends

请求 1 结束

Page is detroyed

Request 2 Start

请求 2 开始

Page is created -> test = "hi"

Request 2 Ends

请求 2 结束

Page is detroyed