The type initializer for 'TestStatic.StaticClass' threw an exception.

今天写程序想实现一个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,有时间需要研究一下为什么...

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值