我有以下代码来编写来自不同函数和subs的一些文本但是一直工作正常但是现在当我从SerialPort DataReceived事件调用委托时我得到了目标参数计数异常。
我无法弄清楚我做错了什么,有什么想法?
Delegate Sub PrintSmsLogDelegate(ByVal NewText As String, ByVal NewLine As Boolean)
Protected Friend Sub PrintSmsLog(ByVal NewText As String, Optional ByVal NewLine As Boolean = True)
If Me.InvokeRequired Then
Dim Txt As New PrintSmsLogDelegate(AddressOf PrintSmsLog)
'Me.Invoke(Txt, NewText)'This fail too
Me.Invoke(Txt, New Object() {NewText}) '<--- TargetParameterCountException
Else
'...
End If
End Sub
Private Sub SmsSerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SmsSerialPort.DataReceived
'... code to receive data and save it in "Lines" variable
Dim Lines as String
Me.PrintSmsLog(Lines, False)
End Sub
答案 0 :(得分:1)
问题是您的PrintSmsLogDelegate
委托声明包含2个必需参数。
所以你必须提供第二个参数。
Invoke
方法的方法签名是这样的:
Function Control.Invoke(method As [Delegate], ParamArray args As Object()) As Object
因此,即使PrintSmsLogDelegate
方法不需要第二个参数,您也应该使用两个参数调用Txt
委托实例(PrintSmsLog
)。
Me.Invoke(Txt, NewText, True)
您无法使用单个数组参数调用Invoke
方法。由于ParamArray
关键字,将自动为您指定的多个参数创建数组。