下面的代码将抛出 InvalidOperationException:ConnectionString 属性尚未初始化。在 Load 方法中调用 Connection.Open() 的行会引发异常。如果我使用 try-finally 语句而不是 using 语句,则一切正常。谁能解释为什么使用语句会发生异常?
Public Class SomeEntity
Private _Connection As SqlClient.SqlConnection
Private _ConnectionString As String
Protected ReadOnly Property Connection() As SqlClient.SqlConnection
Get
If _Connection Is Nothing Then
_Connection = New SqlClient.SqlConnection(_ConnectionString)
End If
Return _Connection
End Get
End Property
Public Sub New(ByVal connectionString As String)
_ConnectionString = connectionString
End Sub
Public Sub Load(ByVal key As Integer)
Using Connection
Connection.Open()
...
End Using
End Sub
End Class