2012-11-18 61 views
0

请看看下面的代码: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关闭关闭连接)不要有数据访问层。在需要时,在业务逻辑 层中打开和关闭连接。我相信这会让代码更易于维护。

如果还有其他选择,请让我知道。

+0

不要吞下异常。 – SLaks

+0

您的功能不会返回任何内容。 – SLaks

+0

您应该得到此代码的编译器警告。不要忽视它。 –

回答

2

试试这个:

Public Function ExecuteDataReader(ByVal castRow As Func(Of IDataRecord, Person)) As IEnumerable(Of Person) 
    Using objCon As New SqlConnection("Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True") 
     Using objCommand as New SqlCommand("SELECT URN FROM Person",objCon) 
     Dim objDR As SqlDataReader 
     objCon.Open() 
     objDR = objCommand.ExecuteReader() 
     Dim ret as New List(Of Person) 
     Do While objDR.Read 
      ret.Add(castRow(objDR)) 
     Loop 
     Return ret 
     End Using 
    End Using 
End Function 

其中A)移除的“错误处理”,它默默吞下错误的坏榜样,B)包裹SqlCommandSqlConnection对象,使他们得到妥善处置,以及c)其实从函数返回一些东西,这是你出错的地方。

+0

谢谢。有了这个解决方案,Person不必实现IEnumerable或IEnumerator。这是因为List实现了这些接口,并且你正在返回一个List? – w0051977

+0

是的,'List(Of T)'实现'IEnumerable(Of T)'。 –

+0

感谢代码+1。我已经更新了这个问题。你能看看我的问题的更新,让我知道你认为最好的选择吗?然后我会回答这个问题。再次感谢。 – w0051977