2016-05-03 27 views
0

我有以下代碼來編寫一些來自不同函數和潛艇的文本,但一直工作正常,但現在我得到目標參數計數異常時,我從SerialPort DataReceived事件調用委託。在委託上的目標參數計數異常Sub

我不明白我在做什麼錯,任何想法?

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 

回答

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關鍵字,數組將自動創建您指定的多個參數。