gpt4 book ai didi

vb.net - 如何让 VB.Net List 类对调用者更灵活

转载 作者:行者123 更新时间:2023-12-04 04:44:20 25 4
gpt4 key购买 nike

我是 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

是否有某种方式对类进行编码,以便可以在不必同时指定 .List 的情况下表达 allSubs - 以及某种表达方式,以便将 x 识别为订阅者类型。

最佳答案

要完成这项工作需要有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

关于vb.net - 如何让 VB.Net List 类对调用者更灵活,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18423899/

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