Vb.net 将列表传递给函数作为参数
我有一个函数可以对列表执行操作,但我不能让它接受多个数据类型。例如:Vb.net 将列表传递给函数作为参数,vb.net,Vb.net,我有一个函数可以对列表执行操作,但我不能让它接受多个数据类型。例如: Public Sub-PopulateListBox(对象列表为列表(VariantType),ListboxToPopulate为Listbox) listboxToPopulate.Items.Clear()'清除列表框中的项目 对于objectList中的每个项目 listboxToPopulate.Items.Add(item.ToString) 下一个 终点 问题是,我有不同类别的列表,如员工、建筑地址等。我无法传
Public Sub-PopulateListBox(对象列表为列表(VariantType),ListboxToPopulate为Listbox)
listboxToPopulate.Items.Clear()'清除列表框中的项目
对于objectList中的每个项目
listboxToPopulate.Items.Add(item.ToString)
下一个
终点
问题是,我有不同类别的列表,如员工、建筑地址等。我无法传递
列表(EmployeeClass)
,因为它说它不能转换为列表(VariantType)
。我还尝试了列出(对象)
,得到了相同的结果。我将首先向您展示一个示例类来演示这个用法
Public Class Coffee
Public Property ID As Integer
Public Property Name As String
Public Property Type As String
Public Sub New(iid As Integer, sname As String, stype As String)
ID = iid
Name = sname
Type = stype
End Sub
Public Overrides Function ToString() As String
Return Name
End Function
End Class
我添加了一个参数化的构造器,以便于获得完全填充的咖啡。您需要添加.ToString覆盖,以便列表框知道要显示什么
这是我的(咖啡)清单的来源
Private Function FillCoffeeList() As List(Of Coffee)
Dim CoffeeList As New List(Of Coffee)
Using cn As New SqlConnection(My.Settings.CoffeeConnection),
cmd As New SqlCommand("Select Top 10 ID, Name, Type From Coffees;", cn)
cn.Open()
Using reader = cmd.ExecuteReader
Do While reader.Read
Dim c As New Coffee(reader.GetInt32(0), reader.GetString(1), reader.GetString(2))
CoffeeList.Add(c)
Loop
End Using
End Using
Return CoffeeList
End Function
正如Hans Passant所评论的,将objectList的数据类型更改为IEnumerable(对象的)
现在我可以将(咖啡)列表传递给PopulateListBox方法
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim CList = FillCoffeeList()
PopulateListBox(CList, ListBox1)
End Sub
我可以访问要转换的基础类型的属性
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim t = ListBox1.SelectedItem.GetType
Select Case t.Name
Case "Coffee"
Dim c = DirectCast(ListBox1.SelectedItem, Coffee)
TextBox1.Text = c.ID.ToString
TextBox2.Text = c.Type
End Select
End Sub
您可以根据需要的类型添加其他案例。可能有更好的方法可以做到这一点。如果列表共享特征,它们是否也共享继承?您看过泛型吗?您需要一个协变类型,
objectList As IEnumerable(Of Object)
完成任务。Hans,这似乎可行,非常感谢。你能把它贴出来吗?这样我就可以把它标记为已回答了?另外,在我将其标记为已回答之前,您能告诉我为什么这样做有效吗?
Private Sub ListBox1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListBox1.SelectedIndexChanged
Dim t = ListBox1.SelectedItem.GetType
Select Case t.Name
Case "Coffee"
Dim c = DirectCast(ListBox1.SelectedItem, Coffee)
TextBox1.Text = c.ID.ToString
TextBox2.Text = c.Type
End Select
End Sub