C# constructor execution order

后端 未结 7 986
渐次进展
渐次进展 2020-11-22 14:57

In C#, when you do

Class(Type param1, Type param2) : base(param1) 

is the constructor of the class executed first, and then the superclass

7条回答
  •  误落风尘
    2020-11-22 15:36

    Not sure if this should be a comment/answer but for those who learn by example this fiddle illustrates the order as well: https://dotnetfiddle.net/kETPKP

    using System;
    
    // order is approximately
    /*
       1) most derived initializers first.
       2) most base constructors first (or top-level in constructor-stack first.)
    */
    public class Program
    {
        public static void Main()
        {
            var d = new D();
        }
    }
    
    public class A
    {
        public readonly C ac = new C("A");
    
        public A()
        {
            Console.WriteLine("A");
        }
        public A(string x) : this()
        {
            Console.WriteLine("A got " + x);
        }
    }
    
    public class B : A
    {
        public readonly C bc = new C("B");
    
        public B(): base()
        {
            Console.WriteLine("B");
        }
        public B(string x): base(x)
        {
            Console.WriteLine("B got " + x);
        }
    }
    
    public class D : B
    {
        public readonly C dc = new C("D");
    
        public D(): this("ha")
        {
            Console.WriteLine("D");
        }
        public D(string x) : base(x)
        {
            Console.WriteLine("D got " + x);
        }
    }
    
    public class C
    {
        public C(string caller)
        {
            Console.WriteLine(caller + "'s C.");
        }
    }
    

    Result:

    D's C.
    B's C.
    A's C.
    A
    A got ha
    B got ha
    D got ha
    D
    

提交回复
热议问题