使用只读值从抽象 class 调用构造函数

Call Constructor from abstract class with readonly values

我正在尝试将此构造函数从 Student 调用到 collegestudent。

这是构造函数:

abstract class Student
{
    public readonly string FirstName;
    public readonly string LastName;
    public readonly string StudentID;

    public Student(string Value)
    {
        FirstName = Value;
        LastName = Value;
        StudentID = Value;
    }

    public string Value
    {
        get { return FirstName + LastName + StudentID; }
    }
}

这是 CollegeStudent:

class CollegeStudent : Student, IMathClass
{
    public Student(string Tim, string russell, string studentid)
    {
        FirstName = Tim;
        LastName = russell;
        studentID = studentid;
    }
}

我收到以下错误

问题可能出在初始化顺序上。 readonly 变量只能赋值一次(当它是 class 变量时在构造函数中)。当您创建对象时,变量将已经由 Student 构造函数初始化,因为它将首先被调用(在 CollegeStudent 的构造函数之前)。当您尝试在 CollegeStudent 构造函数中(再次)初始化它时,它已经初始化,因此会引发错误。

此外,我建议进行一些更改:

首先:使属性不是readonly而只定义publicgetter和private/protectedsetter.这可能已经解决了您的问题。

public string Firstname {get; protected set;}

其次:接下来是你的CollegeStundet的构造函数和参数名。因为这些是参数(包含信息的变量),所以它们看起来很奇怪。更好的是:

public CollegeStudent(string firstName, string lastName, string studentId) 

您将像这样使用它来创建一个新的 CollegeStudent 对象:

// this uses polymorphism as all CollegeStudnet are Student
Student studentX = new CollegeStundet("Tim", "Russel", "123AAA"); 

第三:在默认构造函数中将所有属性设置为相同的值真的很奇怪。一般来说,这绝不是一个好主意。至少提供一个通用构造函数来将所有三个初始化为不同的值。当您已经遵循我的 first 建议时,您仍然可以让它们为“空”(null - 当使用默认构造函数时)。

 Student(string firstName, string lastName, string studentId);

 // the base keyword will pass the values to the constructor of Student
 CollegeStudent(string firstName, string lastName, string studentId) : base(firstName, lastName, studentId) 

但总的来说,我建议在定义它们的 class 中初始化它们(在本例中为 Student 构造函数)。当您需要从外部更改值 Student 并且您确实希望这些值不可写时,您的概念出了问题。