将多个对象添加到VB.net ArrayList

时间:2014-06-29 21:57:47

标签: vb.net object arraylist

我正在VB.net中创建一个简单的程序来保存和阅读客户详细信息;我想将详细信息保存为ArrayList中的对象,然后在需要时检索详细信息。我知道我的程序尚未完成,但我已粘贴下面的代码。我对VB.net很新,所以我提前道歉。谢谢。

以下是我的Customer对象类的代码

Public Class Customer

Private CusID As Integer
Private CName As String
Private PostC As String
Private Phone As String

Public Sub New()

    CusID = 1
    CName = "Anom"
    PostC = "Anom"
    Phone = "Anom"

End Sub

Public Sub New(ByVal cid As Integer, ByVal aCName As String)

    CusID = cid
    CName = aCName

End Sub

Public ReadOnly Property GetCName() As String

    Get
        Return CName
    End Get

End Property

Public WriteOnly Property SCName As String

    Set(ByVal value As String)
        CName = value
    End Set

End Property

Public Overrides Function ToString() As String
    Return "Customer id: " & CusID.ToString() & " Customer name: " & CName
End Function

结束班

这是我将Customer对象保存到数组的代码,该数组在模块的早期定义。不幸的是,对于我添加到阵列的每个新客户,它都会覆盖之前的。

    Sub NewCustomer(ByRef CustL As ArrayList)

    Dim CustomerID As Integer
    Dim CustomerName As String

    Console.WriteLine("Please enter the customer name: ")
    CustomerName = (Console.ReadLine())
    Console.WriteLine("Please enter the customer ID: ")
    CustomerID = CInt(Console.ReadLine())

    CustL.Add(New Customer(CustomerID, CustomerName))

    Console.WriteLine("Press any key to return to the main menu")
    Console.ReadKey()
    Console.Clear()
    Main()

End Sub

这是从阵列中检索客户详细信息的代码。

Sub ViewCustomer(ByRef CustL As ArrayList)

    Dim CustomerID As Integer

    Console.WriteLine("Please enter the customer ID: ")
    CustomerID = CInt(Console.ReadLine())

    'Lookup customer from array here.

    Console.ReadKey("Press any key to return to the main menu")
    Console.Clear()
    Main()

End Sub

1 个答案:

答案 0 :(得分:0)

'你最好切换到一个对象来保存你的客户信息,然后删除ArrayList用于一个强类型的集合。一旦您将每个客户转变为一个对象,您将拥有更多的控制权以及您希望如何处理它们。 如下所示

 Private CustList As New List(Of CustFiles)

 Public Class CustFiles
 Public Property custID As Integer
 Public Property custName As String
 End Class

Public Sub CustQueue(ByVal custName As String, ByVal custID  As Integer)
Dim CustObj As New CustFiles
CustObj .custName = custName 
CustObj.custID  = custID  
CustList.Add(CustObj)
End Sub

    For Each eachCust In CustList 
        MessageBox.Show(eachCust.custID  & " " & eachCust.custName )
    Next