如何在c#中填充数组列表?

 jun_c 发布于 2023-02-10 10:05

我有一个阅读学生记录文件的作业,然后计算并显示每门课程的最终成绩.作为一个老程序程序员,考虑到我们应该从中开始的UML,我很难弄清楚"适当的"(例如,大多数OO)程序流程.一个很大的问题是,这是我第一次实现阵列列表,即使在阅读了Java Tutorials和一堆在线样本之后,我仍然对实际示例有点模糊.我认为学期末的大脑模糊使我无法将这些例子用于这项任务.

这是我到目前为止的地方:

我的主要方法包括

FinalStudentGrade finalGradeReport = new FinalStudentGrade();
finalGradeReport.MainMethod();

它要求Students.PopulateStudents(@"grades.txt")显示成绩报告.PopulateStudents()读取数据文件,通过构造函数创建学生对象,并基于以下数据成员:

string nameFirst;
string nameLast;
string studentID;
ArrayList Earned; 
ArrayList Possible; 
float average;
string letterGrade;

PopulateStudents方法读取文件,为文件中的每一行创建一个Student对象,包括计算的平均值和字母等级.然后需要将这些学生中的每一个添加到List theStudentList;

class Students
{
    List theStudentList;
    public bool PopulateStudents(string @sourceData)   
    {
        String sourcePath = sourceData;
        theStudentList = new List();
        bool success = true;
        try
        {
            StreamReader inputReader = new StreamReader(sourcePath);
            while (inputReader != null)
            {
                String inputLine = inputReader.ReadLine();
                char delim = ',';   
                String[] inputValues = inputLine.Split(delim); 

......我被困......

我正要定义nameFirst = inputValues[1];,nameLast = inputValues[2];,studentID = inputValues[0];等,但后来我意识到,我没有使用构造函数来创建Student对象.

是否需要创建Student.nameFirst=...,然后填充theStudentList这些对象?或者我可以定义theStudentList[recordCounter].nameFirst(recordCounter当然,定义第一个),因为theStudentList它被实例化为List();?最好的方法是什么,我是否以一种好的方式可视化课程之间的程序流程?

1 个回答
  • 好吧,我没有看到定义的构造函数,所以我假设你没有定义一个带参数的构造函数.如果是这种情况,您可以先构造对象,然后设置属性:

    Student s = new Student();
    s.nameFirst = inputValues[1];
    s.nameLast = inputValues[2];
    s.studentID = inputValues[0];
    

    或使用初始化语法

    Student s = new Student() {
        nameFirst = inputValues[1]
        nameLast = inputValues[2]
        studentID = inputValues[0]
        };
    

    如果你确实定义了一个constriuctor(比如说你提到的三个属性),那么只需使用构造函数:

    Student s = new Student(inputValues[1], inputValues[2], inputValues[0]);
    

    然后只需添加创建的学生:

    theStudentList.Add(s);
    

    2023-02-10 10:10 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有