Question

I am trying to build an object that uses System.ComponentModel.ISynchronizeInvoke, which has the method: (amongst others)

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

What is the best way to call the method with the given arguments? I can use:

    public object Invoke(Delegate method, object[] args)
    {
        return method.DynamicInvoke(args);
    }

But this is late bound. My gut instinct is that this is the only way to call the method.. Any ideas?

Was it helpful?

Solution

I think it’s logically impossible for it to be any other way. The method delegate may encapsulate a method of any signature (with any number and type of parameters, and any type of return value or void). The only way to resolve its signature and invoke it with the supplied arguments (after verifying that they’re of the correct quantity and type) would be at run-time through reflection.

If you were not implementing the ISynchronizeInvoke interface and could define your own method, then you could restrict your method argument to only accept method delegates of a particular signature; in that case, you could invoke them directly.

For example, to execute methods that take no parameters and have a return value, you would use:

public TResult Invoke<TResult>(Func<TResult> method)
{
    return method();
}

To execute a method that takes three parameters and has no return value, you would use:

public void Invoke<T1,T2,T3>(Action<T1,T2,T3> method, T1 arg1, T2 arg2, T3 arg3)
{
    method(arg1, arg2, arg3);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top