构造函数的执行 及其顺序

//测试子类实例化时执行的构造函数的顺序
public void DoConstructorTest()

{

    ConstructorTest.StaticMethod();

    ConstructorTest b = new ConstructorTest();

}

 

 

using System;





namespace ConsoleApplicationTest

{

    /// <summary>

/// 静态构造函数在程序中只执行一次
/// 构造函数的执行顺序 子类(静)->父类(静)->父类->子类
/// 调用静态方法之前 只执行其所在类的静态函数

    /// </summary>

    public class ConstructorTestBaseBase

    {

        static ConstructorTestBaseBase()

        {

            Console.WriteLine("ConstructorTestBaseBase  static");

        }

        public ConstructorTestBaseBase()

        {

            Console.WriteLine("ConstructorTestBaseBase  ");

        }

    }

    public class ConstructorTestBase : ConstructorTestBaseBase

    {

        static ConstructorTestBase()

        {

            Console.WriteLine("ConstructorTestBase  static");

        }

        public ConstructorTestBase()

        {

            Console.WriteLine("ConstructorTestBase  ");

        }

        public static void StaticMethod()

        {

            Console.WriteLine("ConstructorTestBase  StaticMethod");

        }

    }

    public class ConstructorTest : ConstructorTestBase

    {

        static ConstructorTest()

        {

            Console.WriteLine("ConstructorTest  static");

        }

        public ConstructorTest()

        {

            Console.WriteLine("ConstructorTest  ");

        }

    }

}

image

你可能感兴趣的:(构造函数)