[英]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.