C# 实例化类以便公共属性可用于页面中的所有事件处理程序?
在不使用会话变量或静态类的情况下,是否可以实例化一个Web表单中所有事件处理程序都可用的类 例如,我的代码如下所示。我实例化汽车并在C# 实例化类以便公共属性可用于页面中的所有事件处理程序?,c#,asp.net,.net,C#,Asp.net,.net,在不使用会话变量或静态类的情况下,是否可以实例化一个Web表单中所有事件处理程序都可用的类 例如,我的代码如下所示。我实例化汽车并在页面加载中设置属性颜色。我知道我无法从其他事件处理程序访问它 我不喜欢使用会话变量,因为它们往往会过期,而这里的用户往往会转到一个页面,然后让它打开一段时间。我总是可以设置会话的超时时间,但我更喜欢在页面的整个生命周期中持续的时间 namespace MyNamespace { public partial class ToErase : System.We
页面加载中设置属性
颜色。我知道我无法从其他事件处理程序访问它
我不喜欢使用会话变量,因为它们往往会过期,而这里的用户往往会转到一个页面,然后让它打开一段时间。我总是可以设置会话的超时时间,但我更喜欢在页面的整个生命周期中持续的时间
namespace MyNamespace
{
public partial class ToErase : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Car myCar = new Car();
myCar.Color = "Black";
}
protected void Button1_Click(object sender, EventArgs e)
{
//Have access to myCar.Color here;
//Response.Write(myCar.Color);
}
}
public class Car
{
public string Color { get; set; }
}
}
您可以按以下方式定义它,然后就可以访问它:-
public partial class ToErase : System.Web.UI.Page
{
private Car myCar;
protected void Page_Load(object sender, EventArgs e)
{
this.myCar = new Car();
this.myCar.Color = "Black";
}
protected void Button1_Click(object sender, EventArgs e)
{
this.myCar.Color = "Blue"; ////You can access it here
//Have access to myCar.Color here;
Response.Write(this.myCar.Color);
}
}
public class Car
{
public string Color { get; set; }
}
我错过什么了吗?刚刚
public partial class ToErase : System.Web.UI.Page
{
private Car myCar;
protected void Page_Load(object sender, EventArgs e)
{....}
}
如果您的问题是关于持久性的,那么在WebForms中,ViewState
会出现在您的脑海中(对于上述内容)
根据用例的不同,在一天结束时,您可以让客户机更多地参与进来,使用基于客户机的持久性(例如DOM存储等)。在一天结束时,客户端会发生类似于单击的事件……ASP.Net为您抽象了其中的大部分内容。如果您查看WebForms页面的源代码,您将看到所有为您带来“魔力”的Javascript
Hth…就持久性而言,类实例和viewstate之间会有区别吗?