C# constructor execution order

后端 未结 7 844
渐次进展
渐次进展 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:48

    The order is:

    • Member variables are initialized to default values for all classes in the hierarchy

    Then starting with the most derived class:

    • Variable initializers are executed for the most-derived type
    • Constructor chaining works out which base class constructor is going to be called
    • The base class is initialized (recurse all of this :)
    • The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc

    Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)

    I have a page with more details if you're interested.

    0 讨论(0)
提交回复
热议问题