请查看以下代码:
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子句来确保对象(在堆上)的引用被设置为空,无论是否抛出异常?
答案 0 :(得分:1)
当从方法引用对象时,不需要将变量设置为Nothing,因为一旦方法调用结束,对象将“无根”并且可用于垃圾收集。当方法调用结束时,堆栈上的所有局部变量都将消失,它们引用的对象将没有对它们的根对引用,使它们可用于垃圾回收。通常,您不需要在.NET中“清空”(通过在vb.net中将它们设置为Nothing
)变量,因为它不依赖于引用计数来管理堆上的对象。
请查看this article,了解内存的分配和释放如何在.NET中运行。