【问题标题】:What happens if you have :base() in the top class?如果你在顶级类中有 :base() 会发生什么?
【发布时间】:2019-02-14 04:20:54
【问题描述】:

如果您将 :base() 放在顶级类中,我无法理解会发生什么。代码是这样的......

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();
  }

我不明白为什么我们需要从头开始(A 级)。那么输出会是什么呢?

【问题讨论】:

    标签: c# constructor this main base


    【解决方案1】:

    默认情况下所有类都继承自System.Object类,所以当在顶级类A中添加base()时,你是在调用对象类的构造函数,这不会造成任何影响。

    【讨论】:

    • @SrđanTodorović This 是构造函数的样子。
    【解决方案2】:

    您的顶级类隐式继承自 System.Object(C# 别名 object)。所以这基本上调用了object的默认构造函数。但是由于无论如何都会默认调用基类的默认构造函数,所以这并没有改变任何东西。

    所以

    public A(int x)
        : base()
    {
    }
    

    public A(int x)
    {
    }
    

    是等价的。

    如果基类构造函数有参数,则必须显式调用它以传递所需的参数。

    见:Using Constructors (C# Programming Guide)

    【讨论】:

      猜你喜欢
      • 2021-01-16
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 2013-01-11
      • 2018-11-05
      相关资源
      最近更新 更多