首页 > 解决方案 > 我希望我的自定义类将日志事件传递给调用者 vb.net

问题描述

我做了一个自定义类来做事。我希望自定义类的调用者处理“写入日志”。最好的方法是什么?,我需要一个事件处理程序,一个委托还是一个动作?,我如何在我的自定义类中传递、保存和调用它。

为了解释我的问题,我已经将我的代码剥离了;

Public Class Form1

    Private Sub WriteToLog(LineToWrite As String)  ' the local log writer
        TextBox1.AppendText(LineToWrite & vbCrLf)
    End Sub


    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WriteToLog("Starting...")
        Dim a As New Yadda(WriteToLog)
        a.CalculateStuff()
    End Sub

    Public Class Yadda

        Sub New(LogWriter As Delegate/eventhanlder/action?)
            ' save the event handler for the local log
            how?
        End Sub

        Private Sub ClassWriteToLog(LineToWrite As String)  ' the logwriter in the class, who should pass the things to write to the local writer
            'Call the passed event to write to the local event log
        End Sub

        Public Sub CalculateStuff()
            For t As Integer = 1 To 100
                For tt As Integer = 1 To 1000000
                    Dim a As Double = 17323 * 43764
                Next
                ClassWriteToLog("Processing step; " & t)
            Next
        End Sub
    End Class
End Class

标签: vb.netclassdelegatesactioneventhandler

解决方案


使用Action评论中提到的可能是最直接的解决方案。以下是如何实现它。

Public Class Form1

    Private Sub WriteToLog(LineToWrite As String)  ' the local log writer
        TextBox1.AppendText(LineToWrite & vbCrLf)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        WriteToLog("Starting...")
        Dim a As New Yadda(AddressOf WriteToLog)
        a.CalculateStuff()
    End Sub

    Public Class Yadda

        Private _LogWriter As Action(Of String)

        Sub New(LogWriter As Action(Of String))
            _LogWriter = LogWriter
        End Sub

        ' You do not need this. You can use _LogWriter directly.
        'Private Sub ClassWriteToLog(LineToWrite As String)  ' the logwriter in the class, who should pass the things to write to the local writer
        '    'Call the passed event to write to the local event log
        'End Sub

        Public Sub CalculateStuff()
            For t As Integer = 1 To 100
                For tt As Integer = 1 To 1000000
                    Dim a As Double = 17323 * 43764
                Next
                _LogWriter("Processing step; " & t)
            Next
        End Sub
    End Class
End Class

您在此处尝试解决的问题有一个常见的解决方案,称为依赖注入。请参阅什么是依赖注入?作为另一种可能的解决方案。


推荐阅读