簡體   English   中英

如何在asp.net頁面中啟動頁面時初始化對象

[英]how to initialize an object at start up of a page in a asp.net page

我需要從一個頁面的啟動初始化一個對象,並在特定的頁面中使用這些對象我該怎么做。

//要初始化的塊

            XTContext.UserContext UContext = new XTContext.UserContext();
            XTContext.Context ctxt = new XTContext.Context();
            XTErrorCollection.ErrorCollection eContext = new XTErrorCollection.ErrorCollection();
            ctxt = (XTContext.Context)Cache["sessionfContext"];
            ctxt.eContext = eContext;
            ctxt.uContext = UContext;

現在我想在頁面內使用ctxt並控制事件。 我嘗試在頁面加載中初始化它但我無法訪問ctxt。

通常,您需要聲明一個您在構造函數或page_load / page_init中實例化的字段。 根據您正在創建的內容,您可能還希望在最后明確地處理資源。

public class MyPage
{
    private object myobject = null;
    public MyPage()
    {
        myobject = new Object();
    }
}

然后,您可以根據需要傳遞給其他類。 如果您需要更強大的功能,或者需要實例存在,您可以從其他無法或不想明確傳遞的對象中使用它,您可以使用IoC容器等作為Castles Windsor,您可以使用它來解析和實例化PerWebRequest資源 - 但它可能需要一些設置並且有自己的怪癖。

試試這個 -

public partial class YourPage : System.Web.UI.Page
{
    XTContext.UserContext UContext; 
    XTContext.Context ctxt; 
    XTErrorCollection.ErrorCollection eContext;


    protected void Page_Load(object sender, EventArgs e)
    {
        UContext = new XTContext.UserContext();
        ctxt = new XTContext.Context();
        eContext = new XTErrorCollection.ErrorCollection();                       

        ctxt = (XTContext.Context)Cache["sessionfContext"];
        ctxt.eContext = eContext;
        ctxt.uContext = UContext;
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM