没有给定的参数对应于 'Person.Person(string, string)' 的所需形式参数 'firstName'

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

好的,我有两个简单的 classes,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; }
}

简单吧?员工继承人,但有问题。员工 class 给我一个错误,指出必须调用 parent class 的构造函数。现在一个类似问题的答案说我应该调用基础 class 的构造函数,它将解决问题。它是做什么的。

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

一本名为 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; }
}

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

这本 2018 年的书 outdated/has 有误吗?难道我做错了什么?或者 C# 中的新更新不允许 child class 如果它不调用 parent 的构造函数?

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

这样的构造函数:

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 class 没有构造函数将符合条件:

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

我同意从 MCSD 认证书中了解更多背景信息可能会有所帮助。

本质上,您的意思是要创建一个没有名字和姓氏的 Employee。但是 EmployeePerson,您必须提供名字和姓氏才能构造 Person

在你的情况下,也许 Employee 没有必要成为 Person 的子类。您是否使用 FirstNameLastName 作为 Employee 的实例?