能否无需静态初始化创建二维数组?学生课程成绩多维数组实现咨询
学生课程成绩存储的数组实现问题
需求与当前问题
需要实现Student对象存储学生已修课程信息:每门课程最多允许3次修读尝试(首次未通过可补考2次),用长度为3的数组记录每次成绩,示例["F", "A", " "]表示首次挂科、二次通过、第三次未修读。
当前代码中,Student类声明了public string[,,] CompletedCourses三维数组,构造函数接收该参数,但实例化时的数组初始化语法错误,同时数组结构也不符合需求场景。
问题1:能否无需静态初始化创建二维数组?
完全可以。你可以先创建指定大小的数组,再逐个赋值,示例代码如下:
// 创建一个2行(对应2门课程)、4列(课程名+3次成绩)的二维数组 string[,] courses = new string[2, 4]; // 给第一门课程赋值 courses[0, 0] = "CS50"; courses[0, 1] = "F"; courses[0, 2] = "B+"; courses[0, 3] = " "; // 给第二门课程赋值 courses[1, 0] = "Psychology 101"; courses[1, 1] = "A"; courses[1, 2] = " "; courses[1, 3] = " ";
这种方式不需要在声明时直接填充数据,适合动态添加课程的场景。
问题2:存储学生课程成绩的多维数组正确实现方式是什么?
你当前使用的三维数组string[,,]并不适配需求,因为三维数组是固定维度的矩形结构,而我们需要的是“单门课程对应一组固定长度的成绩记录”,更适合用以下两种数组结构:
方案1:使用交错数组(数组的数组)
交错数组允许每个元素是独立的数组,刚好对应“课程名+3次成绩”的结构,修改后代码如下:
- 调整
Student类的属性与构造函数参数:
public class Student { public string StudentID { get; set; } public string Name { get; set; } public string Status { get; set; } public Enum StudentMajor { get; set; } public string[][] CompletedCourses { get; set; } // 改为交错数组 public Student(string studentID, string name, string status, Enum studentMajor, string[][] completedCourses) { StudentID = studentID; Name = name; Status = status; StudentMajor = studentMajor; CompletedCourses = completedCourses; } }
- 正确实例化代码:
Student student = new Student( "00069110", "Erling Haaland", "Full-time", Majors.Computer_Information_Systems, new string[][] { new string[] {"CS50", "F", "B+", " "}, // 索引0为课程名,1-3对应三次成绩 new string[] {"Psychology 101", "A", " ", " "} } );
方案2:使用规整的二维数组
如果偏好矩形结构的二维数组,可以将每门课程的信息放在一行,列依次对应课程名、三次成绩,代码如下:
- 调整
Student类属性与构造函数:
public class Student { // ... 其他属性 public string[,] CompletedCourses { get; set; } // 改为二维数组 public Student(string studentID, string name, string status, Enum studentMajor, string[,] completedCourses) { // ... 其他赋值 CompletedCourses = completedCourses; } }
- 实例化代码:
Student student = new Student( "00069110", "Erling Haaland", "Full-time", Majors.Computer_Information_Systems, new string[,] { {"CS50", "F", "B+", " "}, {"Psychology 101", "A", " ", " "} } );
额外推荐:用自定义类封装(更易维护)
纯数组的可读性较差,后续扩展功能(比如添加学分、课程代码)成本高,更推荐创建CourseResult类封装课程信息:
public class CourseResult { public string CourseName { get; set; } public string[] Attempts { get; set; } = new string[3]; // 固定3次尝试 } // 修改Student类 public class Student { // ... 其他属性 public List<CourseResult> CompletedCourses { get; set; } public Student(string studentID, string name, string status, Enum studentMajor, List<CourseResult> completedCourses) { // ... 其他赋值 CompletedCourses = completedCourses; } }
实例化时代码更清晰直观:
Student student = new Student( "00069110", "Erling Haaland", "Full-time", Majors.Computer_Information_Systems, new List<CourseResult> { new CourseResult { CourseName = "CS50", Attempts = new string[] {"F", "B+", " "} }, new CourseResult { CourseName = "Psychology 101", Attempts = new string[] {"A", " ", " "} } } );
内容的提问来源于stack exchange,提问作者Jaiylon
相关产品推荐
相关产品推荐

