【发布时间】:2014-09-04 21:24:24
【问题描述】:
如果不使用 Session 变量或静态类,是否可以在一个 Web 表单中实例化可供所有事件处理程序使用的类?
例如,我的代码如下所示。我实例化 Car 并在 Page_Load 中设置 property 颜色。我知道我无法从另一个事件处理程序访问它。
我不喜欢使用会话变量,因为它们往往会过期,而且这里的用户往往会转到一个页面,然后将其打开一段时间。我总是可以设置会话的超时,但我更喜欢在整个页面的生命周期中持续的东西。
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; }
}
}
【问题讨论】: