2017-06-17 69 views
2

爲了另一個線程更改控制,我需要調用一個委託來改變控制然而,它拋出一個TargetParameterCountException跨線程調用異常

private void MethodParamIsObjectArray(object[] o) {} 
private void MethodParamIsIntArray(int[] o) {} 

private void button1_Click(object sender, EventArgs e) 
{ 
     // This will throw a System.Reflection.TargetParameterCountException exception 
     Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { }); 
     // It works 
     Invoke(new Action<int[]>(MethodParamIsIntArray), new int[] { }); 
} 

爲什麼與MethodParamIsObjectArray調用拋出一個異常?

+0

不知道爲什麼需要'Invoke'考慮到_current線程的'button1_Click'裏面已經是UI thread_ – MickyD

回答

4

這是由於這樣的事實,即Invoke方法具有的簽名:

object Invoke(Delegate method, params object[] args) 

args參數前面的params關鍵字表明,該方法可以採用可變數目的對象作爲參數。當您提供一個對象數組時,它在功能上等同於傳遞多個逗號分隔的對象。下面兩行是功能上等同:

Invoke(new Action<object[]>(MethodParamIsObjectArray), new object[] { 3, "test" }); 
Invoke(new Action<object[]>(MethodParamIsObjectArray), 3, "test"); 

正確的方式來傳遞一個對象數組到Invoke將投數組類型Object

Invoke(new Action<object[]>(MethodParamIsObjectArray), (object)new object[] { 3, "test" }); 
0

Invoke需要包含參數值的對象數組。

在第一次調用中,您沒有提供任何值。你需要一個值,這令人困惑地需要一個對象數組本身。在第二種情況下,需要一個包含整數數組的對象數組。

new object[] { new int[] { } }