web*_*mer 116 c# inheritance constructor constructor-chaining
在C#中,当你这样做时
Class(Type param1, Type param2) : base(param1)
Run Code Online (Sandbox Code Playgroud)
是先执行的类的构造函数,然后调用超类构造函数还是先调用基础构造函数?
Jon*_*eet 163
订单是:
然后从派生程度最高的类开始:
Foo() : this(...)等,则可以有多个构造函数体请注意,在Java中,在运行变量初始值设定项之前初始化基类.如果你曾经移植任何代码,这是一个重要的区别要知道:)
如果您有兴趣,我有一个页面,其中包含更多详细信息.
不确定这应该是评论/答案,但对于那些通过实例学习的人来说,这个小提琴也说明了顺序: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.");
}
}
Run Code Online (Sandbox Code Playgroud)
结果:
D's C.
B's C.
A's C.
A
A got ha
B got ha
D got ha
D
Run Code Online (Sandbox Code Playgroud)