-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 子句来确保对对象(在堆上)的引用设置为空,无论是否抛出异常?

4

1 回答 1

1

当从方法中引用对象时,无需将变量设置为 Nothing,因为一旦方法调用结束,对象将“无根”并且可用于垃圾回收。当方法调用结束时,堆栈上的所有局部变量都将消失,它们所引用的对象将没有对它们的根引用,从而使它们可用于垃圾回收。通常,您不需要Nothing在 .NET 中“清空”(通过在 vb.net 中设置它们)变量,因为它不依赖引用计数来管理堆上的对象。

查看这篇文章,了解如何在 .NET 中分配和释放内存。

于 2013-03-24T12:45:54.193 回答