C#错误:家长不包含一个构造函数的参数0 [英] C# Error: Parent does not contain a constructor that takes 0 arguments

查看:243
本文介绍了C#错误:家长不包含一个构造函数的参数0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的code是

public class Parent
{

    public Parent(int i)
    {
        Console.WriteLine("parent");
    }
}

public class Child : Parent
{
    public Child(int i)
    {
        Console.WriteLine("child");
    }

}

我收到错误:

家长不包含一个构造函数0参数。

Parent does not contain a constructor that takes 0 arguments.

我了解的问题是,与0参数没有构造函数。但我的问题是,为什么我们需要零参数的构造函数?为什么不是没有它的code的工作?

I understand the problem is that Parent has no constructor with 0 arguments. But my question is, why do we need a constructor with zero arguments? Why doesn't the code work without it?

推荐答案

既然你不明确地调用父类的构造为您的孩子类的构造函数的一部分,还有就是插入一个无参数父类的构造隐式调用。该构造函数不存在,所以你会得到错误。

Since you don't explicitly invoke a parent constructor as part of your child class constructor, there is an implicit call to a parameterless parent constructor inserted. That constructor does not exist, and so you get that error.

要纠正这种情况,你需要添加的显式调用:

To correct the situation, you need to add an explicit call:

public Child(int i) : base(i)
{
    Console.WriteLine("child");
}

或者,你可以添加一个无参数的父类的构造:

Or, you can just add a parameterless parent constructor:

protected Parent() { } 

这篇关于C#错误:家长不包含一个构造函数的参数0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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