2016-06-28 62 views
3

我剛開始學習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 

我不t認爲這是你如何使用我設置的列表來添加一個對象。那麼它是如何完成的?語法是否需要調整以添加多個項目?

+1

** [五分鐘介紹類和列表](http://stackoverflow.com/a/34164458/1070452)**可能會有所幫助。我會使用屬性而不是類中的字段:'公共屬性firstname As String'。字段在綁定時不會與屬性相同 – Plutonix

+0

謝謝大家。我認爲這也會真正幫助其他人 – MissDizy

+0

嚴格地說,列表不是*不確定的*長度:你可以用['list.Count()']來確定元素的數量(https://msdn.microsoft.com/ EN-US /庫/ 27b47ht3(v = vs.110)的.aspx)。列表具有自動調整的大小。 –

回答

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)

除此之外還有,你應解決的幾個外殼的錯誤。

+0

啊,我明白了。謝謝。感覺就像我現在有真正的實驗工具 – MissDizy

相關問題