How do I create and call a delegate Action<T> when at runtime I’m receiving the delegate as an object and I know type only at runtime?
For example, In Foo, I define my delegate and want to pass it to a method which receives an Action<int> as an object, along with the data to pass to the delegate. It’s contrived I know, but it’s to demonstrate my problem.
public void Foo()
{
Action<int> handler = i => Console.WriteLine(i + 1);
Process(handler,4)
}
public void Process(object myDelegate, object data)
{
}
and I’d like to call
myDelegate(data)
All the delegate types (Eg.
Action<string>) Are actually types that have anInvoke(...)method.You should look for that invoke method with reflection and call it, It is relatively slow – So watch out.
This should do it :
This works too, I don’t know what is faster, you should check it out :