简体   繁体   中英

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. 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). So what would be the output?

默认情况下,所有类都继承自System.Object类,因此,在顶级类A添加base()时,您在调用对象类的构造函数,则不会产生任何结果。

Your top classes inherit implicitly from System.Object (C# alias object ). So this basically calls the default constructor of 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM