CA2000警告返回值

时间:2014-07-03 20:13:15

标签: vb.net visual-studio-2012 return-value static-analysis ca2000

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

我有一个功能:

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之前添加retVal.Dispose()

 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

tempRetVal = New DisposableObject上会引发CA2000。

1 个答案:

答案 0 :(得分:0)

  

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

为什么呢?你总是定义了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: Dispose objects before losing scope

修改

我相信,由于return块内的TRY语句,您收到了CA2000警告消息。相反,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