CA2000:在丢失范围之前处置对象

时间:2013-06-21 10:11:25

标签: vb.net winforms code-analysis

当我尝试在项目中运行代码分析时,我在这段代码中遇到错误。

//代码

  Private Sub SaveMaterialStatus(ByVal status As String)

        Dim cSMaterialInput As CSMaterialInput = Nothing

        Try

            If ViewState("CSInput") IsNot Nothing Then
                'Create a new transaction
                cSMaterialInput = New CSMaterialInput
                cSMaterialInput = ViewState("CSInput")
                cSMaterialInput.CSStatus = status
                CSMaterialInputMethods.SaveToDatabase(cSMaterialInput, Environment.UserName, Environment.MachineName)

            End If
        Catch ex As Exception
            Throw

        Finally
            If cSMaterialInput IsNot Nothing Then cSMaterialInput.Dispose()

        End Try
    End Sub

详细错误:

CA2000  Dispose objects before losing scope In method 'ShowSummary.SaveMaterialStatus(String)', call System.IDisposable.Dispose on object 'cSMaterialInput' before all references to it are out of scope.   xxxx.CostingTool.Presentation   ShowSummary.aspx.vb 790

我哪里错了?

1 个答案:

答案 0 :(得分:0)

 cSMaterialInput = New CSMaterialInput

问题开始的地方。您立即在下一个语句中重新分配变量,以便您创建的对象永远不会被释放。这引发了CA2000警告。创建一个永远不会使用的新对象是没有意义的。这在方法中几乎没有留下任何其他内容:

  Private Sub SaveMaterialStatus(ByVal status As String)
      Dim cSMaterialInput = ViewState("CSInput")
      If cSMaterialInput IsNot Nothing Then
          cSMaterialInput.CSStatus = status
          CSMaterialInputMethods.SaveToDatabase(cSMaterialInput, Environment.UserName, Environment.MachineName)
      End If
  End Sub

Nothing测试仍然是一个重要的代码味道。当程序试图保存 nothing 时,它只是隐藏了一个错误。