I had a class with some common error handling code, and I wanted to pass in the method and arguments to call, but I couldn’t quite come up with the syntax. What I want to do is roughly this:
private void InvokeHelper(Delegate method, params object[] args) { bool retry = false; do { try { method.DynamicInvoke(args); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); }
and then be able to do things like:
InvokeHelper(foo.MethodA, a, b, c); InvokeHelper(foo.MethodB, x, y );
This gets a compiler error converting foo.MethodA and foo.MethodB into System.Delegate. I came up with the workaround below (and I actually like it better because then I get type checking on my arguments to my methods), but I’m curious if there’s a way to do what I was originally trying to do? I know I could use foo.GetType().GetMethod('MethodA') and invoke that, but I was trying to avoid reflection. I mainly just want to understand how methods are dynamically invoked in .net.
Workaround:
private delegate void EmptyDelegate(); private void InvokeHelper(EmptyDelegate method) { bool retry = false; do { try { method.Invoke(); retry = false; } catch (MyException ex) { retry = HandleException(ex); } } while (retry); }
then call:
InvokeHelper(delegate() { foo.MethodA(a, b, c); }); InvokeHelper(delegate() { foo.MethodB(x, y); });
First off, your signature is
Yet you’re making the mistake that you have to group your args into an array to call this method:
The
parmskeyword tells the compiler to do this for you; you can call this method thusly:Second, if you’re targeting 3.0 or greater, don’t use Delegate, use Action:
and call it this way:
which is just an overall better way of doing this.
As to why you’re getting the compiler issue, its because System.Delegates hate us. Its a simple fact. That, and because there is no implicit cast from method group to Delegate.