派生类显式基本构造函数调用 [英] Derived class explicit base constructor call

查看:118
本文介绍了派生类显式基本构造函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习C#.以下数据来自Microsoft C#帮助网站. 我不明白这句话:如果基类不提供默认的构造函数,则派生类必须通过使用base来对基构造函数进行显式调用."

I am trying to learn C#. The below data is from a Microsoft C# help website. I don't understand this statement, "If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base."

我认为,如果没有用于类的默认构造函数,则C#将自动将默认值分配给int,char或在类中声明的任何内容.如果基类没有构造函数,而有子类,那么最后一句中提到的规则是否不适用?请澄清.

I thought that if there is no default constructor for a class, C# will automatically assign default values to int, char or whatever is declared in a class. If a base class does not have a constructor and it has a child class, does the rule mentioned in the last sentence not apply? Please clarify.

在派生类中,如果未通过使用base关键字显式调用基类构造函数,则默认构造函数(如果存在)被隐式调用.这意味着以下构造函数声明实际上是相同的: C#

In a derived class, if a base-class constructor is not called explicitly by using the base keyword, the default constructor, if there is one, is called implicitly. This means that the following constructor declarations are effectively the same: C#

     public Manager(int initialdata)
     {
         //Add further instructions here.
      }

C#

     public Manager(int initialdata)
    : base()
    {
          //Add further instructions here.
     }

如果基类不提供默认的构造函数,则派生类必须使用base显式调用基构造函数.

If a base class does not offer a default constructor, the derived class must make an explicit call to a base constructor by using base.

推荐答案

如果您没有为类定义构造函数:

If you do not define a constructor for a class:

public class DemoClass
{
   public void SomeFunction() { }
}

C#将为您添加一个默认(无参数)构造函数.在这种情况下;派生类不需要做任何特殊的事情,因为它们将使用提供的默认构造函数.当然,您始终可以定义自己的 own 默认(无参数)构造函数:

C# will add a default (parameterless) constructor for you. In this case; nothing special needs to be done with derived classes, as they will use the provided default constructor. Of course, you can always define your own default (parameterless) constructor:

public class DemoClass
{
   public void DemoClass() { }

   public void SomeFunction() { }
}

由于派生类仍然可以使用它,因此仍然不需要任何特殊的派生类.但是,如果您定义了一个参数化的构造函数,而没有定义默认值:

Which still doesn't require anything special for derived classes, since they can still use it. If however, you define a parameterized constructor, without defining a default:

public class DemoClass
{
   public void DemoClass(string argument) { }

   public void SomeFunction() { }
}

现在没有派生类使用的默认(无参数)构造函数;并且您需要说出要与base一起使用的 构造器:

Now there is no default (parameterless) constructor for derived classes to use; and you need to say which constructor to use with base:

public class DerivedClass : DemoClass
{
   public DerivedClass() : base(String.Empty) { }
}

这篇关于派生类显式基本构造函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆