-1
的請看看下面的代碼:優化配置管理對象
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子句將需要確保對象(在堆上)的引用設置爲空,無論是否拋出異常?
謝謝。 +1。如果你有一個實例變量是一個對象,會發生什麼。當創建它的類被銷燬時,它會被銷燬嗎? – w0051977 2013-03-24 13:02:41
引用類型(類)的實例不會立即「銷燬」。只要沒有「根源」引用,它們就可用於垃圾回收。因此,對於具有實例變量的情況,一旦沒有對持有實例變量的對象的引用,並且沒有其他變量引用實例變量引用的對象,則它所引用的對象將可用於GC。 – PHeiberg 2013-03-24 13:07:48