[英]What happens if you have :base() in the top class?
I am having problems understanding what happens if you put the :base() in top class. 我很难理解如果将:base()放在顶级类中会发生什么。 The code goes like this... 代码像这样...
class A {
public A(): this(3) {
Console.Write("1");
}
public A(int x): base() {
Console.Write("{0}", x);
}
}
class B:A {
public B(): this(4) {
Console.Write("3");
}
public B(int x) {
Console.Write("{0}", x):
}
}
class C:B {
public C(int x): base() {
Console.Write("{0}", x):
}
public C(): this(7) {
Console.Write("6");
}
}
class Program {
public static void Main(string[] args) {
C c = new C();
}
I don't get why we need to start from the top (class A). 我不明白为什么我们需要从头开始(A类)。 So what would be the output? 那么输出是什么?
默认情况下,所有类都继承自System.Object
类,因此,在顶级类A
添加base()
时,您在调用对象类的构造函数,则不会产生任何结果。
Your top classes inherit implicitly from System.Object
(C# alias object
). 您的顶级类从System.Object
(C#别名object
)隐式继承。 So this basically calls the default constructor of object
. 因此,这基本上调用了object
的默认构造object
。 But since the default constructor of the base class is called by default anyway, this doesn't change anything. 但是由于无论如何默认都会调用基类的默认构造函数,因此这不会改变任何内容。
So 所以
public A(int x)
: base()
{
}
and 和
public A(int x)
{
}
are equivalent. 是等效的。
If a base class constructor has parameters, then you must call it explicitly to pass the required parameters. 如果基类构造函数具有参数,则必须显式调用它以传递必需的参数。
See: Using Constructors (C# Programming Guide) 请参阅: 使用构造函数(C#编程指南)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.