asp教程.net 頁面static變數問題
static變數只在第一次使用時才初始化(可能早於也可能晚於Main函數).c中的全域變數存在早於main函數.
static有修飾限定詞,全域變數無.
static的機制複雜得多,其初始化次序有可能引起競爭問題(比如兩個類的static成員的初始化都依賴對方時),全域變數不存在這些問題.
測試代碼如下:
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 = "這是個static變數賦值"+DateTime.Now;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.TextBox1.Text = str;
}
}
我用Firefox連續開啟3個頁面點擊按鈕顯示的值都是同樣的(把串連賦值到IE下值就變了)
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 = "這是個static變數賦值"+DateTime.Now;
ViewState["Key"] = "這是個static變數賦值" + DateTime.Now;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
this.TextBox1.Text = ViewState["Key"].ToString();
}
}
這種情況下,需要的極有可能就是個ViewState或者是Session。
Application與static變數
Application是通過一個集合儲存所有的對象。
強型別:
Application中儲存的是object,對對象的儲存和使用需要作cast動作。對於實值型別更需要Box&UnBox。對效能的影響較大。
而static變數是強型別的對象。
改為ViewState正常
非泛型類並且非ThreadStatic的static變數在一個AppDomain中只存在一份
換而言之,不同AppDomain裡面的同一個static變數可以不同
泛型類的static變數是每個具體類型一個
ThreadStatic的static變數是每個線程一個
至於能不能訪問,要看變數的存取修飾詞和所在類的存取修飾詞
static變數不是一直存在的,clr會在使用這個變數之前幫你準備好
因此在使用這個變數之前並不知道它是否存在,唯一可以知道的是在使用時,它一定存在(當然可能是null)
至於什麼時候clr準備好這個靜態變數,又有BeforeFieldInit和非BeforeFieldInit的區別