Is it possible to created a method that takes ANY method (regardless of it's parameters) as a parameter? The method would also have a params
parameter which then takes all the parameters for the parameter-method.
So basically what I want is something like this:
public void CallTheMethod(Action<int> theMethod, params object[] parameters)
But then for any method, not just for methods that takes an int.
Is something like this possible?
Thanks
Yes, with a delegate:
public object CallTheMethod(Delegate theMethod, params object[] parameters)
{
return theMethod.DynamicInvoke(parameters);
}
But see Marc Gravell's comment on your question :)
Well, you could pass the non-specific
Delegate
, butDynamicInvoke
is sloooooowwwwww (relatively speaking)
It's possible, but not what should be done.
This is what I would do:
public void CallTheMethod(Action toCall)
You might go "huh". Basically, what it lets the user do is this:
CallTheMethod(() => SomeOtherMethod(with, some, other, parameters));
However, if you want it to return a type, it involves generics:
public void CallTheMethod<T>(Func<T> theMethod)
You can put generic constraints on that type, do whatever you want with it, etc.
Yes. You can use DynamicInvoke to call the methods:
Action<int> method1 = i => { };
Func<bool, string> method2 = b => "Hello";
int arg1 = 3;
bool arg2 = true;
//return type is void, so result = null;
object result = method1.DynamicInvoke(arg1);
//result now becomes "Hello";
result = method2.DynamicInvoke(arg2);
A method to do this would become:
object InvokeMyMethod(Delegate method, params object[] args)
{
return method.DynamicInvoke(args);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With