zoukankan      html  css  js  c++  java
  • 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

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

  • 相关阅读:
    bzoj 3993: [SDOI2015]星际战争
    bzoj 4066: 简单题
    bzoj 3611: [Heoi2014]大工程
    bzoj 3530: [Sdoi2014]数数
    bzoj 3529: [Sdoi2014]数表
    bzoj 3504: [Cqoi2014]危桥
    bzoj 3489: A simple rmq problem
    bzoj 3211: 花神游历各国
    bzoj 3196: Tyvj 1730 二逼平衡树
    bzoj 3172: [Tjoi2013]单词
  • 原文地址:https://www.cnblogs.com/foamliu/p/2171038.html
Copyright © 2011-2022 走看看