创建一个类构造函数,该构造函数基于参数 (C#) 初始化其他类型的对象变量



我是编码新手,所以我希望这很清楚......

我创建了两个新班级:一个学生和一个成绩簿。它们的构造函数如下:

Student(string studentName, string gradeBookTitle);
Gradebook(double testWeight, double quizWeight, 
          double assignmentWeight, string[] studentNameArray);

我想使用 Gradebook.studentNameArray 参数中的名称为每个名称初始化一个 Student 对象。这样,当用户创建成绩簿时,他们将自动为班级中的每个学生创建一个 Student 对象。

但是,我遇到了问题,因为您无法使用数组的内容来命名新变量。我假设我想多了...有没有更简单的方法来组织所有这些?或者在构造函数中创建这些学生变量的另一种方法?

您可以使用

DictionaryKey是学生的姓名。有点像这样(在这里做一些假设,但希望这能告诉你基本的想法):

public IDictionary<string, Student> StudentDictionary { get; set; }
public Gradebook(double testWeight, double quizWeight, 
                 double assignmentWeight, string[] studentNameArray) {
    StudentDictionary = new Dictionary<string, Student>();
    foreach (var name in studentNameArray) {
        StudentDictionary.Add(name, new Student(name, <age_here>, this.Title));
    }
}

User..学生是否有另一个构造函数,或者要在构造函数中设置哪些默认值。这样的事情是可以做到的。

class Gradebook
{
    public Gradebook(double testWeight, double quizWeight, double assignmentWeight, string[] studentNameArray)
    {
        this.TestWeight = testWeight;
        this.QuizWeight = quizWeight;
        this.AssingmentWeight = assignmentWeight;
        this.Students = new List<Student>();
        foreach(var name in studentNameArray)
            Students.Add(new Student(
                studentName: name, 
                age: 0,
                gradeBookTitle: ""
                )
            );
    }
    public double TestWeight { get; set; }
    public double QuizWeight { get; set; }
    public double AssingmentWeight { get; set; }
    public IList<Student> Students { get; set; }
}
class Student
{
    public Student(string studentName, int age, string gradeBookTitle)
    {
    }
}

您可以从 studentNameArray 填充构造函数中的 Student 类型列表。但是,字段年龄不会以这种方式设置。如果还想设置年龄,则需要返回并修改列表或将 studentNameArray 参数更改为 List 类型的参数。

private List<Student> _students;
private string _title;
public Gradebook(double testWeight, double quizWeight, 
          double assignmentWeight,  string[] studentNameArray)
{
    this._testWeight = testWeight;
    this._quizWeight = quizWeight;
    this._assignmentWeight = assignmentWeight;
    this._students = new List<Student>;
    foreach(var name in studentNameArray)
    {
        _students.Add(new Student(name, 0, this._title);
    }
}

相关内容

最新更新