asp.net 頁面static變數問題

來源:互聯網
上載者:User

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的區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.