c# - 没有给出与 'firstName' 所需的形参 'Person.Person(string, string)' 相对应的参数

标签 c# oop inheritance constructor default-constructor

好的,我有两个简单的类:Person 和 Employee。

人:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

员工:

public class Employee : Person
{
    public string DepartmentName { get; set; }
}

简单吧?职员继承人,但是有问题。员工类给我一个错误,指出必须调用父类的构造函数。现在类似问题的答案说我应该调用基类的构造函数,它将解决问题。确实如此。

我的问题是,当员工类本身没有自己的构造函数时,为什么我应该调用基类的构造函数?

一本名为 MCSD Certification 70-483 的书说:

One oddity to this system is that you can make an Employee class with no constructors even though that allows the program to create an instance of the Employee class without invoking a Person class constructor. That means the following definition for the Employee class is legal:

public class Employee : Person
{
 public string DepartmentName { get; set; }
}

我的情况和这本书上写的一模一样。书上说,如果子类没有自己的构造函数,继承而不调用基类的构造函数是合法的。为什么我仍然收到此错误?即使我有相同的实现。

这本 2018 年的书是否已过时/有错误?难道我做错了什么?或者 C# 中的新更新不允许子类如果不调用父类的构造函数?

最佳答案

看起来这是一个错字。因为继承中派生类型的每个构造函数都应该隐式或显式调用基构造函数。

像这样的构造函数:

public Employee () {}

隐含的是:

public Employee () : base() {}

但是,Person 没有无参数构造函数,因此这是错误的原因:

CS7036 There is no argument given that corresponds to the required formal parameter 'firstName' of 'Person.Person(string, string)'

可以做的是创建具有默认值的构造函数:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName = null, string lastName = null)
    {
        FirstName = firstName;
        LastName = lastName;
    }
}

然后没有构造函数的 Employee 类将符合条件:

public class Employee : Person
{
     public string DepartmentName { get; set; }
}

关于c# - 没有给出与 'firstName' 所需的形参 'Person.Person(string, string)' 相对应的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59511462/

相关文章:

javascript - 从实例变量名中找出实例变量名

c++ - 在包含不同子类的 vector 中的某些对象上调用函数

Java私有(private)字段的继承

c# - 为什么我的 Controller 中的 FormCollection 是空的?

c# - Asp.net FileUpload问题 "Arithmetic operation resulted in an overflow."ContentLength始终为-2

c# - 如何保护 Web API 免受数据检索而不是来自资源所有者的数据检索

c++ - 如何指定继承类的构造函数定义?

c# - C#中的算术异常

c++ - 为什么在声明对象时既不执行构造函数也不执行赋值运算符?

python - 如何使 math 和 numpy 模块中的现有函数支持用户定义的对象?