今天写程序想实现一个Singleton模式,结果程序老是抛异常说"The type initializer for 'TestStatic.StaticClass' threw an exception.",InnerException是"Object reference not set to an instance of an object",后来发现犯了一个非常低级的错误,代码如下:
// In main.cs
static void Main()
{
string t = StaticClass.StrMember;
System.Diagnostics.Debug.WriteLine(t);
...
}
// StaticClass.cs
private StaticClass(int defValue)
{
Trace.WriteLine("StaticClass ctor");
IntMember = defValue;
}
private static StaticClass _instance = new StaticClass(12);
private int intMember;
public static int IntMember
{
set
{
Trace.WriteLine("set IntMember");
_instance.intMember = value;
}
}
看出问题了吗?问题就出在
IntMember = defValue;
这句话,为这个静态属性赋值的时候其实是为静态成员_instance的intMember成员赋值,而此时_instance还是null,必须等待构造函数结束以后_instance才会被赋值为新建StaticClass对象的引用。所以应该把
IntMember = defValue;
改写为
this.intMember = defValue;
就一切正常了。调了很久,实在是很郁闷...
总结如下:首先当然是编程水平问题 :P,对Singleton模式一知半解。另外在构造函数里初始化静态属性也不是可取的做法。第三,之所以调试了很久,是因为Visual Studio没有明确的定位异常发生的代码段:总是在main函数的"string t = StaticClass.StrMember;"语句处报异常,非常的misleading,有时间需要研究一下为什么...