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

时间:2013-09-17 17:39:23

标签: 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

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

改变这个:

Private Messages As List(Of String)

对此:

Private Messages As New List(Of String)()

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