为什么有必要一个基类有一个接受0 args的构造函数? [英] Why is it necessary for a base class to have a constructor that takes 0 args?

查看:71
本文介绍了为什么有必要一个基类有一个接受0 args的构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不会编译:

namespace Constructor0Args
{
    class Base
    {
        public Base(int x)
        {
        }
    }

    class Derived : Base
    {
    }

    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

相反,我收到以下错误:

Instead, I get the following error:


'Constructor0Args.Base'不包含带有0个参数的构造函数。

'Constructor0Args.Base' does not contain a constructor that takes 0 arguments

一个基类有必要拥有一个拥有0个参数的构造函数。

Why is that? Is it necessary for a base class to have a constructor that takes 0 arguments?

推荐答案

em> - 问题是,它需要调用一些基础构造函数,以初始化基类型,默认是调用 base ()。你可以通过在derived-types构造函数中自己指定特定的构造函数(和参数)来调整它:

It isn't - the problem is that it needs to call some base constructor, in order to initialise the base type, and the default is to call base(). You can tweak that by specifying the specific constructor (and arguments) yourself in the derived-types constructor:

class Derived : Base
{
    public Derived() : base(123) {}
}

对于 base (或者)构造函数的参数,您可以使用:

For parameters to base (or alternatively, this) constructors, you can use:


  • 参数添加到当前构造函数

  • 文字/常量

  • 静态方法调用(也涉及上述)

  • parameters to the current constructor
  • literals / constants
  • static method calls (also involving the above)

有效,使用上面所有三个项目符号:

For example, the following is also valid, using all three bullets above:

class Derived : Base
{
    public Derived(string s) : base(int.Parse(s, NumberStyles.Any)) {}
}

这篇关于为什么有必要一个基类有一个接受0 args的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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