使用列表而不是数组来创建类中的对象

时间:2016-06-28 14:12:32

标签: vb.net list

我刚开始学习OOP,我想知道是否可以使用列表而不是数组创建对象。该列表似乎有大量的方法,这些方法非常有用,并且可能具有不确定的长度 所以,这就是我所拥有的

Class STUDENT
    'establish properties / members
    Public firstname As String
    Public surname As String
    Public DOB As Date
End Class

'declare a variable of the data type above to put aside memory
Dim students As List(Of STUDENT)

Sub Main()
    Dim selection As Char
    While selection <> "C"
        Console.WriteLine("Welcome to student database")
        Console.WriteLine("Number of students: " & students.Count)
        Console.WriteLine(" (A) Add a student")
        Console.WriteLine(" (B) View a student")
        Console.WriteLine(" (C) Quit")

        selection = Console.ReadLine.ToUpper

        If selection = "A" Then
            Console.Write("Please enter a firstname: ")
            students.firstname.add= Console.ReadLine
...etc
END While

此行导致问题

students.firstname.add= Console.ReadLine

我不认为这是使用我设置的列表添加对象的方式。那怎么办?语法是否需要调整以添加多个项目?

1 个答案:

答案 0 :(得分:3)

此行存在多个问题:students.firstname.add= Console.ReadLine

打破它我们有:

students.firstname.addadd = Console.ReadLine

您首先需要学生对象。 students.firstname不存在。

Dim tempStudent = New STUDENT()
tempStudent.firstname = Console.ReadLine()
' Other property assignments, etc

完全创建学生对象后,将其添加到列表中。添加是一种方法,因此我们使用括号:

students.Add(tempStudent)

除此之外,您还应该解决一些套管错误。