NETT

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

static constructor
========================
首先看一段代码:

namespace Learning.Static
{
    class StaticTesting
    {
        static void Main(string[] args)
        {
            test t1 = new test();
            test t2 = new test();
            Console.WriteLine(test.count);
        }
    }
    class test
    {
        public static int count;
        static test()
        {
            count++;
        }
        public test()
        {
            count++;
        }
    }
}

Q:Console 输出结果几?why?
有的同学说是4,因为每次new的时候都会执行构造函数,这个test class 有两构造函数,new 了两次肯定是4了.
也有的同学说是3.
A:3
那为什么是3而不是4呢,这就需要我们探究一下test类中的静态构造函数了.

首先让我们稍微修改一下test class 的代码,如下:
  class test
    {
        public static int count;
        static test()
        {
            count++;
            Console.WriteLine("static test()");
        }
        public test()
        {
            count++;
            Console.WriteLine("test ()");
        }
    }

再次运行代码,结果如下
static test()
test ()
test ()
3
很明显,test class 的静态构造函数只执行了一次,虽然我们在Main中New 了两个实例出来.

上MSDN:
A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically

before the first instance is created or any static members are referenced.

1)A static constructor does not take access modifiers or have parameters.
  不能带参数和访问修饰.

2)A static constructor is called automatically to initialize the class before the first instance is created or any static members are referenced.
  这句告诉我们,静态构造函数是在new出第一个实例或引用静态成员之前就被调用了.对于上面的例子,如果我们按F11单步执行,跟踪count就会发现在new t1调用Public test()之前它的值已经为1了.
  如果我们把Main()函数修改如下:
   static void Main(string[] args)
        {
            Console.WriteLine(test.count);
            Console.Read();
        }
  那么这时候输出的count值就是1了(因为没有new,非静态的构造函数没有被调用),虽然我们没有new instance出来但通过调用test的静态成员test.count同样会执行test的静态构造函数.

3)A static constructor cannot be called directly.

4)The user has no control on when the static constructor is executed in the program.

5)A typical use of static constructors is when the class is using a log file and the constructor is used to write entries to this file.

6)Static constructors are also useful when creating wrapper classes for unmanaged code, when the constructor can call the LoadLibrary method.

7)If a static constructor throws an exception, the runtime will not invoke it a second time, and the type will remain uninitialized for the lifetime of the application domain in which your program is running.

通过上面的描述,大家应该明白了.

posted on 2010-05-08 08:53  nett  阅读(239)  评论(0编辑  收藏  举报