【发布时间】:2011-06-21 19:51:57
【问题描述】:
如果我在 ASP.NET 2.0 中将此类定义为应用程序的一部分:
public class Foo
{
private static int _seed = 100;
private static object myLock = new object();
public Foo()
{
lock (myLock)
{
this.MyInt = _seed;
_seed++;
}
}
public int MyInt {get; set;}
}
(编辑:已更新以解决答案指出的线程安全问题)
该静态成员将如何表现?它会从 100 开始并为每个会话单独增加,还是会为每次页面刷新单独增加,还是全局...?
注意:我问这个问题是因为我第一次在我的 ASP.NET 应用程序中使用类来建模数据,而且我已经发现 C# 的引用性质似乎被 ViewState 序列化忽略了,所以我想知道我还能期待什么其他奇怪的事情。例如,如果我定义了这个类(假设Bar 是另一个类):
public class OtherFoo
{
public List<Bar> Bars {get; set;}
}
我在我的页面上这样做:
OtherFoo _myFoo = new OtherFoo();
//Code here to instantiate the list member and add some instances of Bar
Bar b = _myFoo.Bars[0];
ViewState["myFoo"] = _myFoo; //Assume both are [Serializable]
ViewState["myBar"] = b;
当我在下一次回发时将它们从 ViewState 中取出时,b 和 _myFoo.Bars[0] 不再是同一个对象。
【问题讨论】: