vb.net - 我希望我的自定义类将日志事件传递给调用者 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
解决方案
使用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
您在此处尝试解决的问题有一个常见的解决方案,称为依赖注入。请参阅什么是依赖注入?作为另一种可能的解决方案。
推荐阅读
- php - 为什么从只读的 php 文件中回显输入会在一行上打印?
- php - Symfony 向多个收件人发送电子邮件 SwiftMailer
- javascript - libuv和V8中的NodeJs事件循环?
- r - 使用gtsummary :: tbl_svy_summary时如何报告未加权的缺失值数量?
- java - 使用 Maven 创建带有依赖项的 jar 时,“错误:缺少 JavaFX 运行时组件,需要运行此应用程序”
- r - R中列表的Rowbind列表
- regex - powershell 正则表达式错误
- javascript - 如何删除树中的单身儿童?
- typescript - 打字稿泛型作为对象键名
- mysql - 具有两个 IN 运算符的 SQL 查询,比较按索引执行