C#的构造函数

做项目时偶尔需要知道C#中构造函数的执行顺序,随手写了一段代码:

   1:      class Program
   2:      {
   3:          class A
   4:          {
   5:              static A()
   6:              {
   7:                  Console.WriteLine("A static ctor");
   8:              }
   9:   
  10:              public A()
  11:              {
  12:                  Console.WriteLine("A ctor");
  13:              }
  14:   
  15:          }
  16:   
  17:          class B : A
  18:          {
  19:   
  20:              static B()
  21:              {
  22:                  Console.WriteLine("B static ctor");
  23:              }
  24:   
  25:              public B()
  26:                  : base()
  27:              {
  28:                  Console.WriteLine("B ctor");
  29:              }
  30:          }
  31:   
  32:          class C : B
  33:          {
  34:   
  35:              static C()
  36:              {
  37:                  Console.WriteLine("C static ctor");
  38:              }
  39:   
  40:              public C()
  41:                  : base()
  42:              {
  43:                  Console.WriteLine("C ctor");
  44:              }
  45:          }
  46:   
  47:          static void Main(string[] args)
  48:          {
  49:              new C();
  50:          }
  51:      }

 

执行结果:

image

 

动态和静态构造函数在调用链上正好反序,想想也对,静态是一碰就会执行的嘛。

posted on 2011-09-08 14:14  薛定谔的旺财(刘杨)  阅读(244)  评论(0编辑  收藏  举报

导航