下面是源代码:  
  public class Counter
    {
        private   int num = 0 ;
        static private Counter counter = null;
        private Counter() {
            Console.WriteLine("the class Counter has been instaned!");
        }        static public Counter getInstance()
        {
            if (counter!= null)
                return new Counter();
            else return counter;
        }        public   int count() {
            return num++;
        }
       }就是一个计数器,然后让不同的线程调用它,调用代码如下:
public static void ThreadProc()
    {
        for (int i = 0; i < 10; i++)        {
          
                Console.WriteLine("ThreadProc: {0}", Counter.getInstance().count());
           
                // Yield the rest of the time slice.
            Thread.Sleep(0);
            
        }
    }可是报的错误是System.NullReferenceException: 未将对象引用设置到对象的实例
麻烦哪位大虾帮忙解决一下

解决方案 »

  1.   

    new Counter().getInstance().count()
    或静态类
      

  2.   

    不好意思,错误刚找到了 是这句if (counter!= null) 出了问题,应该是 if (counter== null) 
    但现在又出现新问题了,就是不同的线程启动之后,输出的值都是0,好像num根本没有增加,这是怎么回事啊!
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
    the class Counter has been instaned!
    ThreadProc: 0
      

  3.   

    问题找出来,太马虎了,呵呵
    这个方法写错了,应该是这样
       static public Counter getInstance()
            {
                if (counter == null)
                    counter = new Counter();            return counter;
            }
    谢谢楼上的两位
      

  4.   

    囧,刚刚发现了一个可以GPS定位手机位置的网站,真不可思议!可以去看看
    http://hd.qu365.com/?P382933