在C#中,当你这样做
Class(Type param1, Type param2) : base(param1)
是先执行类的构造函数,然后调用超类构造函数,还是先调用基构造函数?
发布于 2009-12-11 01:43:26
它将首先调用基构造器。还要记住,如果你不把:base(param1)
放在你的构造函数后面,基类的空构造函数就会被调用。
发布于 2009-12-11 01:43:56
首先调用基类的构造函数。
发布于 2016-08-17 04:05:06
不确定这是否应该是一个评论/答案,但对于那些通过示例学习的人来说,这个小提琴也说明了顺序: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.");
}
}
结果:
D's C.
B's C.
A's C.
A
A got ha
B got ha
D got ha
D
https://stackoverflow.com/questions/1882692
复制相似问题