静态成员之静态构造函数

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 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/ttnet/archive/2010/05/08/1730258.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值