0

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

我通过在 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

ErrorHandler 类内容:

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
4

2 回答 2

1

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

于 2013-09-17T17:46:29.460 回答
0

改变这个:

Private Messages As List(Of String)

对此:

Private Messages As New List(Of String)()

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

于 2013-09-17T18:04:45.363 回答