我是编码的新手,所以我希望这很清楚......
我创建了两个新课程:学生和成绩册。他们的构造者如下:
Student(string studentName, string gradeBookTitle);
Gradebook(double testWeight, double quizWeight,
double assignmentWeight, string[] studentNameArray);
我想使用Gradebook.studentNameArray参数中的名称为每个名称初始化Student对象。这样,当用户创建成绩簿时,他们会自动为班级中的每个学生创建一个学生对象。
但是,我遇到了问题,因为您无法使用数组的内容来命名新变量。我假设我正在思考它......是否有更简单的方法来组织所有这些?或者在构造函数中创建这些学生变量的另一种方法是什么?
答案 0 :(得分:1)
您可以使用Dictionary
,Key
是学生的姓名。有点像这样(在这里做一些假设,但希望这能告诉你基本的想法):
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));
}
}
答案 1 :(得分:1)
用户..学生是否有其他构造函数或要在构造函数中设置哪些默认值。这样的事情可以做到。
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)
{
}
}
答案 2 :(得分:0)
您可以从studentNameArray中填充构造函数中Student类型的List。但是,现场年龄不会这样设定。如果您也想设置年龄,则需要返回并修改列表或将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);
}
}