gpt4 book ai didi

vb.net - 将对象添加到数组列表

转载 作者:行者123 更新时间:2023-12-01 09:36:02 25 4
gpt4 key购买 nike

我在将对象添加到数组列表时遇到了一些问题。

基本上,该对象有两个属性(文件 ID/名称),但我不知道如何分配这些属性。在运行时,它会因未找到对象的公共(public)成员而出错。

Private QueueList As New ArrayList
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
Dim QueueObj As New Object
QueueObj.FileID = "Test 1"
QueueObj.FileName = "Test 2"
QueueList.Add(QueueObj)
End Sub

我还想知道如何在数组列表上进行循环并访问每条记录上的两个属性。

谢谢!

最佳答案

您不能只使用“对象”。您需要构建自己的类:

Public Class File
Public Property FileID As Integer
Public Property FileName As String
Public Sub New ()
End Sub
Public Sub New(ByVal FileName As String, ByVal FileID As Integer)
Me.FileID = FileID
Me.FileName = FileName
End Sub
End Class

然后像这样构建你的队列:

Private QueueList As New ArrayList()
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
QueueList.Add(New File(FileName, FileID))
End Sub
Public Sub Queue(ByVal FileObj As File)
QueueList.Add(FileObj)
End Sub

或者,更好的是,使用泛型:

Public QueueList As New List(Of File)()
Public Sub Queue(ByVal FileName As String, ByVal FileID As Integer)
QueueList.Add(New File(FileName, FileID))
End Sub
Public Sub Queue(ByVal FileObj As File)
QueueList.Add(FileObj)
End Sub

然后,遍历列表:

For Each item As File In QueueList
'Console.WriteLine(item.FileID & vbTab & item.FileName)
Next item

关于vb.net - 将对象添加到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7727156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com