0

我知道这已经讨论过很多次,但似乎没有解决方案有效,所以我认为并且可能值得尝试重新打开它,因为已经过了一段时间。

我有一个功能:

Public Function Test() As Object
    Dim retVal As DisposableObject
    Dim tempRetVal As DisposableObject
    Try
        tempRetVal = New DisposableObject
        retVal = tempRetVal
        tempRetVal = Nothing
        Return retVal
    Catch
        tempRetVal.Dispose()
        Throw
    Finally
        tempRetVal.Dispose()
    End Try
End Function

如您所见,有很多 Dispose 语句。这是因为我试图找到一种让它工作的方法。我发现的唯一方法(显然不是解决方案)是retVal.Dispose()在返回 retval 之前添加。

 Public Function Test() As Object
    Dim retVal As DisposableObject
    Dim tempRetVal As DisposableObject
    Try
        tempRetVal = New DisposableObject
        retVal = tempRetVal
        tempRetVal = Nothing
        retVal.Dispose()
        Return retVal
    Catch
        tempRetVal.Dispose()
        Throw
    Finally
        tempRetVal.Dispose()
    End Try
End Function

任何提示将不胜感激!:)

注意:我使用的是 VS2012

编辑: 我也尝试了 MS 提出的简单模板,但它也不起作用:

Public Function Test() As Object
    Dim retVal As DisposableObject
    Dim tempRetVal As DisposableObject
    Try
        tempRetVal = New DisposableObject
        retVal = tempRetVal
        tempRetVal = Nothing
        Return retVal
    Finally
        if tempRetVal isnot Nothing then tempRetVal.Dispose()
    End Try
End Function

CA2000 被抛出tempRetVal = New DisposableObject

4

1 回答 1

0

我发现的唯一方法(显然不是解决方案)是在返回 retval 之前添加 retVal.Dispose()。

为什么?无论如何,您已经finally定义了一个块。让 finally 块负责处理。您的代码应如下所示。还,

 Public Function Test() As Object
    Dim retVal As LLServerConnection
    Dim tempRetVal As LLServerConnection
    Try
        tempRetVal = New LLServerConnection
        retVal = tempRetVal
        tempRetVal = Nothing
        Return retVal
    Catch
        Throw
    Finally
        If Not tempRetVal Is Nothing Then
        tempRetVal.Dispose()
    End Try
End Function

有关详细信息,请参阅CA2000:在失去范围之前处置对象

编辑:

return我相信,由于块内的语句,您会收到 CA2000 警告消息TRY。相反,return您的子程序之前的对象实际上结束了。请参阅下面的代码,并在更改中添加了注释。现在会好起来的。

Public Function Test() As DisposableObject //Change object to actual type DisposableObject
    Dim retVal As DisposableObject = Nothing
    Dim tempRetVal As DisposableObject = Nothing

    Try
        tempRetVal = New DisposableObject()
        retVal = tempRetVal
        tempRetVal = Nothing

    Finally
      If Not tempRetVal Is Nothing Then
         tempRetVal.Dispose()
      End If 

    End Try

        Return retVal //Return the object before your subroutine ends

End Function
于 2014-07-03T20:24:31.770 回答