Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoking System.Delegate class object in C#

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?

like image 776
Rob Avatar asked May 12 '12 19:05

Rob


People also ask

How do I invoke a delegate?

Create the delegate and matching procedures Create a delegate named MySubDelegate . Declare a class that contains a method with the same signature as the delegate. Define a method that creates an instance of the delegate and invokes the method associated with the delegate by calling the built-in Invoke method.

How do you call a delegate in C#?

In C# 3.0 and later, delegates can also be declared and instantiated by using a lambda expression, as shown in the following example. // Instantiate Del by using a lambda expression. Del del4 = name => { Console. WriteLine($"Notification received for: {name}"); };

Can delegates be used as callbacks?

Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.

Which delegate can hold and invoke multiple methods?

If a delegate has do not return any value, it is a multicast delegate that can invoke multiple methods.


1 Answers

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);
}
like image 67
Douglas Avatar answered Sep 21 '22 23:09

Douglas