C# 错误:父级不包含采用 0 个参数的构造函数 [英] C# Error: Parent does not contain a constructor that takes 0 arguments
问题描述
我的代码是
public class Parent
{
public Parent(int i)
{
Console.WriteLine("parent");
}
}
public class Child : Parent
{
public Child(int i)
{
Console.WriteLine("child");
}
}
我收到错误:
Parent 不包含采用 0 个参数的构造函数.
Parent does not contain a constructor that takes 0 arguments.
我理解问题在于 Parent
没有带有 0 个参数的构造函数.但我的问题是,为什么我们需要一个零参数的构造函数?为什么没有它代码就不能工作?
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屋!