在 C# 中创建一个使用两个 类 的对象列表

Creating a List of Objects in C# that use two classes

我的网站有 table 行。每行有两列值。我想要做的是将每一行存储到列表中自己的位置,并让用户能够在列表中输入值并单独访问每一列值,即;不只是制作一串行。最终代码将包含一个 for 循环以循环遍历行和网络抓取代码,但为了排除故障我省略了它并且只是对值进行硬编码。我从 2 个 class 开始,一个用于 getter/setters 个人 class 值,另一个用于 get/set 该对象。从那里我创建了一个方法来设置值。

        public class Student
        {
            public string Name { get; set; }
            public string Address { get; set; }
        }

        public class ListOfStudents
        {
            public Student student { get; set; }
        }

        public static ListOfStudents GetListOfStudents()
        {
            List<Student> students = new List<Student>();
            Student student = new Student
            {
                Name = "Mike",
                Address = "Main St"
            };            
            ListOfStudents listOfStudents = new ListOfStudents
            {
                students.Add(Student)
            };
            return listOfStudents;
        }

我收到这个错误"Cannot initialize type 'ListClass.ListOfStudents' with a collection initializer because it does not implement System.Collections.IEnumerable"基本上我无法确定如何制作对象列表。

您忘记使用列表

public class ListOfStudents
{
    public List<Student> Students { get; set; }
}

和其他代码:

List<Student> students = new List<Student>();
Student student = new Student
{
    Name = "Mike",
    Address = "Main St"
}; 
students.Add(Student);           
ListOfStudents listOfStudents = new ListOfStudents
{
    Students = students;
};

Edit

但是你的代码很奇怪,请说出你真正想要的

你的代码有错误,因为 students 不是 ListOfStudents 的 propertie 不要忘记 ListOfStudents 的学生属性假设要成为列表,您可以使用下面的代码

    public class Student
    {
        public string Name { get; set; }
        public string Address { get; set; }
    }

    public class ListOfStudents
    {
        public List<Student> Students { get; set; }
    }

    public static ListOfStudents GetListOfStudents()
    {
        List<Student> students = new List<Student>();
        Student student = new Student
        {
            Name = "Mike",
            Address = "Main St"
        };
        students.Add(student);
        ListOfStudents listOfStudents = new ListOfStudents()
        {
            Students = students
        };
        return listOfStudents;
    }

作为当前上下文中的 .net 开发人员,我建议使用所谓的 Indexer

Indexer :

An indexer is a special type of property that provides access to a class or structure in the same way as a table for its internal collection. This is the same as the property except that it has been defined with this keyword with square brackets and parameters.

[来源] https://www.tutorialsteacher.com/csharp/csharp-indexer

如何在您的上下文中使用索引器的示例:

 public class Student
 {
    public string Name { get; set; }
    public string Address { get; set; }
 }

 public class ListOfStudents
 {
    public Student[] Students = new Student[100];

    public Student this[int index]
    {
        get { return Students[index]; }
        set { Students[index] = value; }
    }
 }