我是VB.Net中的泛型和集合的新手。我编写了第一个创建自定义对象列表的类。虽然它似乎有用,但我相信我已经用粗略的方式完成了它,我想知道如何为需要调用它的代码改进它。这是列表类的基本部分:
Public Class Subscribers
Public List As New List(Of Subscriber)
Public Sub New()
Dim sConnDatabase As String = ConfigurationManager.ConnectionStrings("DatabaseConnString").ConnectionString
Dim connection As New SqlConnection(sConnDatabase)
Dim cmd As SqlCommand
cmd = New SqlCommand("SELECT * FROM dbo.Subscriber_v", connection)
cmd.CommandType = CommandType.Text
connection.Open()
Dim objReader As SqlDataReader = cmd.ExecuteReader()
Do While objReader.Read()
Dim id As Integer = objReader("SubscriberID")
Dim s As Subscriber = New Subscriber(id)
List.Add(s)
Loop
objReader.Close()
connection.Close()
End Sub
End Class
这是我使用该课程的第一个小测试:
Dim n As String
Dim d As Integer
Dim allSubs As New Subscribers()
For Each Subscriber In allSubs.List
n = Subscriber.SubscriberName
d = Subscriber.DaysUntilExpired.ToString()
Next
有关改进的具体问题是:如何使调用者能够编写如下代码:
For Each x In allSubs
n = x.SubscriberName
d = x.DaysUntilExpired.ToString()
Next
是否有某种方法对类进行编码,以便可以表达allSub而无需同时指定.List - 以及表达它的某种方式,使得x将被识别为类型为Subscriber。
答案 0 :(得分:3)
要完成这项工作,需要Subscribers
实施IEnumerable(Of Subscribers)
。实现可以转发到List
字段
Public Class Subscribers Implements IEnumerable(Of Subscriber)
Public Function GetEnumerator() As IEnumerator(Of Subscriber) _
Implements IEnumerable(Of Subscriber).GetEnumerator
Return List.GetEnumerator()
End Function
Private Function GetEnumerator1() As IEnumerable _
Implements IEnumerable.GetEnumerator
Return List.GetEnumerator()
End Function
End Class