2011-06-09 47 views
0

我在MSDN上提到了document。我明白「.BeginInvoke」確實,但是看着示例代碼在文檔嘗試瞭解MSDN上的Control.BeginInvoke代碼

Delegate Sub MyDelegate(myControl As Label, myArg2 As String) 

Private Sub Button_Click(sender As Object, e As EventArgs) 
    Dim myArray(1) As Object 

    myArray(0) = New Label() 
    myArray(1) = "Enter a Value" 
    myTextBox.BeginInvoke(New MyDelegate(AddressOf DelegateMethod), myArray) 
End Sub 'Button_Click 

Public Sub DelegateMethod(myControl As Label, myCaption As String) 
    myControl.Location = New Point(16, 16) 
    myControl.Size = New Size(80, 25) 
    myControl.Text = myCaption 
    Me.Controls.Add(myControl) 
End Sub 'DelegateMethod 

委託myDelegate(和DelegateMethod)接受一個控制和一個字符串,但是,在.BeginInvoke,一個Label控件傳遞一個數組...

myTextBox.BeginInvoke(New MyDelegate(AddressOf DelegateMethod), myArray) 

,並在「DelegateMethod」有

myControl.Text = myCaption 

應該不是一個字符串傳遞而非陣列?我錯過了什麼嗎?

回答

3

BeginInvoke可以接受兩個參數。一個是代表,在這種情況下AddressOf DelegateMethod。其他參數是參數數組。 DelegateMethod接受兩個參數:一個標籤和一個字符串。爲了使用begininvoke傳遞這些參數,將包含兩個成員的對象數組傳遞給beinginvoke以匹配方法的參數:一個標籤和一個字符串。

因此,無論標籤和字符串中使用此陣

+0

那麼它不應該是myTextBox.BeginInvoke傳遞(新MyDelegate(AddressOf DelegateMethod),myArray的(1))...? – 2011-06-09 18:21:16

+1

不是因爲幾個原因。首先是myArray(1)是一個不是數組的對象,並且不符合子定義。第二個是如果你只是用這個字符串創建一個數組,那麼DelegateMethod將不會收到標籤。標籤被傳入陣列中,我認爲這可能是您混淆的根源。 「委託myDelegate(和DelegateMethod)接受一個控件和一個字符串,但是,在.BeginInvoke,一個Label控件被傳遞並且一個數組...」不正確。一個委託和一個數組被傳入 – 2011-06-09 19:16:29

1

您的代碼是正確的。該框架代表您從對象數組中適當地轉換參數。