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