简体   繁体   English

如果您在顶级类中有:base()会怎样?

[英]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.

相关问题 在基类中标记ToString虚拟,会发生什么? - Marking ToString virtual in base class, what happens? 在Polymorphism中,只有派生类可以作为基类,这里发生了什么? - In Polymorphism only derived class can be the base class, what happens here? 当您需要派生 class 字段值但您只有基本 class 字段变量时使用什么设计模式? - What design pattern to use when you need derived class field values but you only have base class field variables? 如果一个类实现了两个扩展同一个基接口的接口会发生什么? - What happens if a class implements two interfaces that extend the same base interface? 如果 class 没有构造函数会怎样? 在 C# - What happens if a class doesn't have a constructor? in C# Eric Lippert的意思是“您需要知道基类是什么来确定基类是什么”? - What does Eric Lippert mean by “you need to know what the base class is to determine what the base class is”? 如果你突破Lock()语句会发生什么? - What happens if you break out of a Lock() statement? 等待同步方法时会发生什么 - What happens when you await a synchronous method 当您绑定到ItemSource时,内部会发生什么? - What happens internally when you bind to ItemSource? 如果启动太多线程会发生什么? - What happens if you start too many threads?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM