Is there a way to send a any method as a parameter? I need to do it for all kind of method, not caring about signatures and returns. Say something like this (bad code, just for the idea):
public class Foo
{
...
void TestMethod(DontKnowWhatToPutHere theDelegate) {}
...
}
...
foo.TestMethod(-foo.AnotherMethod(1,2)-);
foo.TestMethod(-foo.AnotherMethod("I don't care method signature nor returning type")-);
I tried with no success to do it with Action as parameter.
What I need to do is to send any method to a function, and then use reflection to get method name and parameters, so if there’s another way you guys can figure out, I would gladly hear about it too.
No. The compiler always has to be able to identify a specific delegate to convert to, and there’s no single delegate type which is compatible with all method signatures. You can get a long way by using
Action,Action<T>,Action<T1, T2>etc, thenFunc<TResult>,Func<T1, TResult>etc… but even that’s going to fail when it comes tooutandrefparameters. Additionally, there’s overload resolution to consider.Additionally, your syntax is passing the result of a method invocation, which isn’t the same thing as passing a method in the first place. (That’s ignoring the
-prefix/suffix, which appears to be made-up syntax.)What you could use is
Expression<Action>and wrap the method call:Then:
Within
TestMethodyou can then look into the expression tree to find out that it’s a method call, work out the target, the parameters etc. See the MSDN page on expression trees for more information.