我目前正在编写一些使用 MethodInfo.Invoke()
的代码使用反射执行方法。我需要捕获发生的异常,并且不想 edit any Visual Studio exception handling settings这样做。
我读过其他 StackOverflow 文章( Reflection MethodInfo.Invoke() catch exceptions from inside the method 和 How can I create an Action delegate from MethodInfo? ),它们说明了通过创建委托(delegate)并执行该委托(delegate)而不是调用 Invoke()
来解开调用的能力。 .
我遇到的问题是我不知道我正在调用的方法的方法签名;它可以有一个返回类型,或者返回 void,并且可以有多个参数,也可以没有。
考虑以下代码:
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();
}
}
鉴于这种情况,我一直在思考如何创建合适的 Action<Tᴺ>
或Func<Tᴺ, out TResult>
(其中 ᴺ == 参数数量)
最佳答案
创建一个动态方法来完成工作并从动态方法创建委托(delegate)。
例如,想象一个方法
static public int Add(int a, int b)
{
return a+b;
}
使用 DynamicMethod 执行以下操作:
static public object Add(object[] parameters)
{
return Add((int)parameters[0], (int)parameters[1]);
}
并创建发出方法的委托(delegate)。
var myDelegate = MyDynamicMethod.CreateDelegate(typeof(Func<object[], object>)) as Func<object[], object>:
您必须使用反射来了解签名才能发出足够的 DynamicMethod。
关于c# - 如何从 MethodInfo 创建 Action<Tᴺ> 或 Func<Tᴺ, out TResult>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27419080/