public class MySingleton
{
private static readonly MySingleton _theOneAndOnly;
static MySingleton()
{
_theOneAndOnly = new MySingleton();
}
public static MySingleton TheOnly
{
get{ return _theOneAndOnly; }
}
/// <summary>
/// Private constructor to avoid object created from outside
/// </summary>
private MySingleton()
{}
}
对于静态成员何时被初始化,其实仔细看我上一个单元所说的对象构造步骤就可以分析出来。可能看起来比较抽象,尤其在分析嵌套关系的时候,现在就举一个例子来进行说明。
class A
{
public static int X = B.Y;
static A()
{
++X;
}
}
class B
{
public static int Y = A.X;
static B()
{
++Y;
}
}
那么大家先猜猜如下调用输出结果是什么。
Debug.WriteLine( A.X.ToString() );
Debug.WriteLine( B.Y.ToString() );
其结果是“2,1”,也就是A.X的值为2,而B.Y的值为1。