C# 错误:父级不包含采用 0 个参数的构造函数
我的代码是
public class Parent
{
public Parent(int i)
{
Console.WriteLine("parent");
}
}
public class Child : Parent
{
public Child(int i)
{
Console.WriteLine("child");
}
}
我收到错误:
父级不包含带有 0 个参数的构造函数。
我知道问题是 Parent
没有带有 0 个参数的构造函数。但我的问题是,为什么我们需要一个零参数的构造函数?为什么没有它代码就无法工作?
My code is
public class Parent
{
public Parent(int i)
{
Console.WriteLine("parent");
}
}
public class Child : Parent
{
public Child(int i)
{
Console.WriteLine("child");
}
}
I am getting the error:
Parent does not contain a constructor that takes 0 arguments.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于您没有显式调用父构造函数作为子类构造函数的一部分,因此会隐式调用插入的无参数父构造函数。该构造函数不存在,因此您会收到该错误。
要纠正这种情况,您需要添加显式调用:
或者,您可以只添加无参数父构造函数:
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:
Or, you can just add a parameterless parent constructor:
您需要将子类的构造函数更改为:
您收到错误是因为父类的构造函数采用参数,但您没有将该参数从子类传递给父类。
C# 中的构造函数不是继承的,您必须手动链接它们。
You need to change your child's constructor to:
You were getting the error because your parent class's constructor takes a parameter but you are not passing that parameter from the child to the parent.
Constructors are not inherited in C#, you have to chain them manually.
您需要将
child
类的构造函数更改为::base(i)
部分表示基类的构造函数具有一个int 参数。如果缺少此内容,则隐式告诉编译器使用不带参数的默认构造函数。由于基类中不存在这样的构造函数,因此会出现此错误。
You need to change the constructor of the
child
class to this:The part
: base(i)
means that the constructor of the base class with oneint
parameter should be used. If this is missing, you are implicitly telling the compiler to use the default constructor without parameters. Because no such constructor exists in the base class it is giving you this error.编译器无法猜测应该为基本构造函数参数传递什么。你必须明确地这样做:
The compiler cannot guess what should be passed for the base constructor argument. You have to do it explicitly:
您可以在父类中使用不带参数的构造函数:
You can use a constructor with no parameters in your Parent class :
默认情况下,编译器尝试调用基类的无参数构造函数。
如果基类没有无参数构造函数,则必须自己显式调用它:
参考:继承期间构造函数调用层次结构
By default compiler tries to call parameterless constructor of base class.
In case if the base class doesn't have a parameterless constructor, you have to explicitly call it yourself:
Ref : Constructor calling hierarchy during inheritance