0

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

//代码

  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

我哪里错了??

4

1 回答 1

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 测试仍然有明显的代码气味。当您的程序试图不保存任何内容时,它只是隐藏了一个错误。

于 2013-06-21T10:56:29.690 回答