Refer. It can be said that all instances of this class share a static variable. The Asp.net page is a class, and we access a page. An instance of this class will be instantiated on the server to respond to our requests. "All instances share a static variable", which means that the static variable on the Asp.net page accessed by all clients is the same variable.
Every time we access the Asp.net page, it is a brand new object, not the object we accessed last time. Therefore, the changes to the variables on the page were not retained during the last page access. When this problem occurs, many beginners intuitively declare this variable as static. During the test, they find that the page status is actually retained.
TestCodeAs follows:
View code
Public Partial Class _ Default: system. Web. UI. Page
{
Private Static String STR;
Protected Void Page_load ( Object Sender, eventargs E)
{
If ( ! Ispostback)
{
Str = " This is a static variable value assignment. " + Datetime. now;
}
}
Protected Void Button#click ( Object Sender, eventargs E)
{
This . Textbox1.text = STR;
}
}
I used Firefox to open three pages in a row and click the button to display the same value (assign the connection value to IE and then change it)
View code
Public Partial Class _ Default: system. Web. UI. Page
{
// Private Static string STR;
Protected Void Page_load ( Object Sender, eventargs E)
{
If ( ! Ispostback)
{
// STR = "this is a static variable value assignment" + datetime. now;
Viewstate [ " Key " ] = " This is a static variable value assignment. " + Datetime. now;
}
}
Protected Void Button#click ( Object Sender, eventargs E)
{
This . Textbox1.text = Viewstate [ " Key " ]. Tostring ();
}
}
Changed to viewstate.