请看下面的代码:
Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim p1 As Person
Try
p1 = New Person
p1.DoSomething()
objCommand = New SqlCommand
Using objCommand
Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True"
objCon = New SqlConnection
Using objCon
objCon.ConnectionString = strConString
objCon.Open()
objCommand.Connection = objCon
objCommand.CommandText = "select startdate from person "
Dim objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
objDR.Read()
Using objCon
Dim startdate As String = objDR("startdate")
End Using
End If
End Using
End Using
Catch ex As Exception
Throw
Finally
If objCon.State = ConnectionState.Open Then
objCon.Close()
End If
objCon = Nothing
objCommand = Nothing
p1=Nothing 'This line is still needed
End Try
End Sub
我知道 finally 子句中的代码毫无意义,因为连接和命令都包含在 Using 语句中。
但是,如果您有自己的自定义类(如 Person)不使用非托管资源,会发生什么情况?在这个实例中肯定需要 FINALLY 子句来确保对对象(在堆上)的引用设置为空,无论是否抛出异常?