I am currently writing some code which uses MethodInfo.Invoke()
to execute a method using reflection. I need to catch exceptions if they occur, and do not want to edit any Visual Studio exception handling settings to do so.
I have read other StackOverflow articles (Reflection MethodInfo.Invoke() catch exceptions from inside the method and How can I create an Action delegate from MethodInfo?) which illustrate the ability to unwrap the invocation by creating a delegate, and executing that instead of calling Invoke()
.
The problem I have is that I don't know the method signature of the method I am calling; It could have a return type, or return void, and it could have several parameters, or none.
Consider the following code:
public void Run(object instance, MethodInfo method)
{
object[] parameters = CreateParameters(method);
object result = default(object);
try
{
result = method.Invoke(context, parameters);
}
catch(Exception ex)
{
// Never happens because VS does not catch exceptions thrown by Invoke();
}
}
Given this scenario, I'm stuck with exactly how to create an appropriate Action<Tᴺ>
or Func<Tᴺ, out TResult>
(where ᴺ == number of parameters)