请看看下面的代码:VB.NET - 介绍了IEnumerator
'Form1.vb
Imports System.Data.SqlClient
Public Class Form1
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'ExecuteDataReader(Function(x) New Person With {.URN = x("URN")})
Try
Dim results As IEnumerable(Of Person) = ExecuteDataReader(Function(x) New Person With {.URN = x("URN")})
For Each c As Person In results 'Line 4
Next
Catch ex As Exception
Finally
End Try
End Sub
Public Function ExecuteDataReader(ByVal castRow As Func(Of IDataRecord, Person)) As IEnumerable(Of Person)
Try
Dim objCon As New SqlConnection("Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True")
Dim objCommand As New SqlCommand
Dim objDR As SqlDataReader
objCon.Open()
objCommand.Connection = objCon
objCommand.CommandText = "SELECT URN FROM Person"
objDR = objCommand.ExecuteReader()
Do While objDR.Read
castRow(objDR)
Loop
Catch ex As Exception
End Try
End Function
End Class
'Person.vb
Public Class Person
'Implements IEnumerator, IEnumerable
Public URN As String
End Class
为什么我是新来IEnumberators结果变量上线4空。我使用的.NET版本(3.5)不允许使用Yield关键字。
更新 Damien_The_Unbeliever纠正了代码。你认为这种模式适用于数据逻辑层吗?我相信我有四种选择:
1)返回数据表而不是数据读取器到业务逻辑 图层。然后我可以将代码封装在Using语句中。
2)使用Damien_The_Unbeliever的答案(不包括使用语句中的 可丢弃对象)中描述的模式 将业务逻辑层的数据读取器返回。
3)将数据返回读者 业务对象层,只有当 DataReader的是即dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
4关闭关闭连接)不要有数据访问层。在需要时,在业务逻辑 层中打开和关闭连接。我相信这会让代码更易于维护。
如果还有其他选择,请让我知道。
不要吞下异常。 – SLaks
您的功能不会返回任何内容。 – SLaks
您应该得到此代码的编译器警告。不要忽视它。 –