Reputation: 5420
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); });
Upvotes: 2
Views: 1230
Reputation: 110161
Here's a re-write, following Will's advice to use Action:
private void InvokeHelper(Action method)
{
bool retry = false;
do
{
try
{
method();
retry = false;
}
catch (MyException ex)
{
retry = HandleException(ex);
}
} while (retry);
}
public void Test()
{
FooClass foo = new FooClass();
InvokeHelper( () => foo.MethodA(1, "b", 3) );
InvokeHelper( () => foo.MethodB(2, "y"));
}
Upvotes: 2
Reputation:
First off, your signature is
private void InvokeHelper(Delegate method, params object[] args)
Yet you're making the mistake that you have to group your args into an array to call this method:
InvokeHelper(foo.MethodA, new object[] { a, b, c});
The parms
keyword tells the compiler to do this for you; you can call this method thusly:
InvokeHelper(foo.MethodA, a, b, c);
Second, if you're targeting 3.0 or greater, don't use Delegate, use Action:
private void InvokeHelper(Action method)
and call it this way:
InvokeHelper(()=> MyMethodToInvoke(a, b, c));
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.
Upvotes: 4