代码在 Using 块中使用我的类时过早地跳转到 Dispose()

  • 本文关键字:Dispose Using 代码 vb.net
  • 更新时间 :
  • 英文 :


我有一个自定义类来处理应用程序中的错误。 在其中,我有几种用于添加错误详细信息和生成/附加错误日志的方法。 代码非常简单,但我对某些事情感到困惑。

我通过在 using 块中实例化错误处理类来生成错误日志。 代码执行完第一个方法后,它会直接跳转到Dispose,仅此而已。

编辑:显然我不够清楚..删除了我上面的例子。 这是我代码的精简版本:

用法(阅读我的笔记):

Dim Message as String
Using Err as New ErrorHandler(ex,"Custom Message")
    Err.Add("Some detail about the error") <-- DOES THIS, THEN DISPOSES
    Err.Add("Another detail about the error") <--NEVER GETS EXECUTED
    Message = Err.WriteLog() <--NEVER GETS EXECUTED
End Using

错误处理程序类内容:

Imports System.IO
Imports System.Text
Public Class ErrorHandler
    Implements IDisposable
    Public FriendlyMessage As String = String.Empty
    Public Exception As System.Exception = Nothing
    Private Messages As New List(Of String)
    Public Sub New(ByVal Exception As System.Exception, Optional ByVal FriendlyMessage As String = "")
        Me.Exception = Exception
        Me.FriendlyMessage = FriendlyMessage
    End Sub
    Public Sub Add(ByVal Message As String)
        Messages.Add(Message)
    End Sub
    Public Function WriteLog() As String
        ..... formats and writes to log file ..... 
        Return output
    End Function
    Private disposedValue As Boolean = False
    Protected Overridable Sub Dispose(ByVal disposing As Boolean)
        If Not Me.disposedValue Then
            ....... clean up ........
        End If
        Me.disposedValue = True
    End Sub
#Region " IDisposable Support "
    ' This code added by Visual Basic to correctly implement the disposable pattern.
    Public Sub Dispose() Implements IDisposable.Dispose
        ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
        Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
#End Region
End Class

如果我必须猜测(我必须这样做,因为我不知道ErrorHandler类是什么样子的),我会说Messages还没有被实例化。

更改以下内容:

Private Messages As List(Of String)

对此:

Private Messages As New List(Of String)()

您没有实例化列表,因此当您尝试向列表添加消息时,它会抛出NullReferenceException。 未处理的异常将导致它离开Using块,这将调用 Dispose 方法。

最新更新