Question

I'm trying to call Invoke with a array as parameter.
The problem is that Invoke uses the params - if my array is 3 elements long, Invoke tries to call a method with 3 parameters instead of calling the method with one ARRAY parameter:

private void something(Control[] dataDropControls) {
   // ...
   this.Invoke(new Action<Control[]>(initControls), dataDropControls);
}

private void initControls(Control[] controls) {
    // ...
}

(This question does not answer my question, because the parameter array is build in the calling function. Im my case, the function gets the already built array.)

Q: How can I call Invoke so that it can call the method with one array parameter?

Était-ce utile?

La solution

Assuming Invoke tries to call the delegate dynamically, you should be able to wrap the input array in another

private void Invoke(Action<Control[]> act, Control[] elements)
{
    act.DynamicInvoke(new object[] { elements });
}

This issue is caused by array covariance, since you can do

Control[] elements = ...
object[] arr = elements;

so the input Control[] can be passed directly to Invoke, which results in each array elements being passed separately to the method.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top