Explain the syntax of calling a C # delegate

In the code at this link: http://c-sharp-programming.blogspot.com/2008/07/cross-thread-operation-not-valid.html , the delegate is used to update the value of the text field from the workflow.

I basically see what happens, but the syntax for this line is:

label1.Invoke(del, new object[] { newText });

bothers me. Can someone explain this please? Why do we use the syntax of a new array of objects for the delegate when there is only one parameter?

Full code:

delegate void updateLabelTextDelegate(string newText);
private void updateLabelText(string newText)
{
 if (label1.InvokeRequired)
 {
     // this is worker thread
     updateLabelTextDelegate del = new updateLabelTextDelegate(updateLabelText);
     label1.Invoke(del, new object[] { newText });
 }
 else
 {
     // this is UI thread
     label1.Text = newText;
 }
}
+3
source share
4 answers

TL DR:

Control.Invokecalls DynamicInvoke of your delegate, which takes an array of objects to work with any type of delegate.

//

# . . , 1 arg () (void). updateLabelText sig. :

updateLabelTextDelegate del = new updateLabelTextDelegate(updateLabelText);

:

updateLabelTextDelegate del = updateLabelText;

del, updateLabelText Control.Invoke.

label1.Invoke(del, new object[] { newText });

params, Control.Invoke, object[]

label1.Invoke(del, newText);

Invoke , . (, string, ). del updateLabelText :

del(newText);

:

updateLabelText(newText);

Control.Invoke del, , , , . - :

, invocal :

del.DynamicInvoke(args);

args - object[]. , - ( Delegate), .

+4

Control.Invoke, , params Object[] args. object[] args .

+3

Invoke. updateLabelTextDelegate string, , .

, ,

label1.Invoke(del, newText)

.

+2

-, , Invoke - Invoke . , Control.Invoke, :

public Object Invoke(
    Delegate method,
    params Object[] args
)

, . , , Action<string, string, int> - , :

control.Invoke(someDelegate, new object[] { "foo", "bar", 10 });

So the answer is that it object[]exists to ensure generality, because the delegate type also remained common. This is a bit like MethodInfo.Invoke- not knowing at compile time how many parameters there are, a type value object[]is the best way to resolve various situations.

+1
source

All Articles