循环遍历对象列表并打印

时间:2018-03-11 15:08:37

标签: c# .net

我正在尝试循环遍历Course对象并将它们显示到控制台。出于某种原因,我的解决方案似乎不起作用,任何人都可以检测到我可能导致此问题的任何明显问题吗?谢谢:))

class Course
{
    private int v1;
    private string v2;
    private string v3;
    private int v4;

    public Course(int v1, string v2, string v3, int v4)
    {
        this.v1 = v1;
        this.v2 = v2;
        this.v3 = v3;
        this.v4 = v4;
    }

    public int courseCode { get; set; }
    public string courseName { get; set; }
    public string professor { get; set; }
    public int capacity { get; set; }
}

class Computation
{
   public static List<Course> courses = new List<Course>();

    public static void addCourse(Course c)
    {
        courses.Add(c);
    }

    public static void viewCourses()
    {
        foreach(var c in courses)
        {
            Console.WriteLine(c.courseName);
        }
    }
}

主要

 static void Main(string[] args)
         {
             Course computerScience = new Course(1, "Computer Science", "Dr Shkhla", 200);
             Course mathematics = new Course(2, "Mathematics", "Dr Shkhla", 200);
             Course physics = new Course(3, "Physics", "Dr Shkhla", 200);

             addCourse(computerScience);
             addCourse(mathematics);
             addCourse(physics);
             viewCourses();                 
         }

3 个答案:

答案 0 :(得分:1)

问题是你永远不会为这些属性分配任何东西。此外,现在是学习标准命名约定的好时机:

public class Course
{
    public Course(int code, string name, string professor, int capacity)
    {
        Code = code;
        Name = name;
        Professor = professor;
        Capacity = capacity;
    }

    // properties should be in PascalCase
    // and should not have their entity's name as prefix 
    public int Code { get; set; }
    public string Name { get; set; }
    public string Professor { get; set; }
    public int Capacity { get; set; }
}

大部分时间都应避免使用代码中的序列(v1v2等)。
另外,请注意我从类中删除了未使用的属性。

答案 1 :(得分:0)

将构造函数更改为:

public Course(int courseCode, string courseName, string professor, int capacity)
{
    this.courseCode = courseCode;
    this.courseName = courseName;
    this.professor = professor;
    this.capacity = capacity;
}

答案 2 :(得分:0)

您需要更新构造函数:

public Course(int v1, string v2, string v3, int v4)
{
    courseCode = v1;
    courseName = v2;
    professor = v3;
    capacity = v4;
}

或直接设置您的媒体资源:

Course computerScience = new Course
{
  courseCode = 1,
  courseName  = "Computer Science",
  professor = "Dr Shkhla",
  capacity = 200
};

如果您想要更好的控制台输出,请覆盖toString()模型的Course功能。

public override string ToString()
{
    return $"Course {courseCode}: {courseName} by {professor}. Capacity: {capacity}";
}
相关问题