13

我想动态调用一个MethodInfo对象,并让从它内部抛出的任何异常向外传递,就好像它被正常调用一样。

我似乎有两个选择。它们概述如下。

选项 1维护 抛出的异常的类型MyStaticFunction,但StackTrace由于throw.

选项 2维护StackTrace异常的 ,但异常的类型始终为TargetInvocationException。我可以拉出InnerException和它的类型,但这意味着我不能写这个,例如:

try { DoDynamicCall(); }
catch (MySpecialException e) { /* special handling */ }

选项1:

void DoDynamicCall()
{
    MethodInfo method = /*referencing MyClass method void MyStaticFunction(int x)*/;
    try
    {
        method.Invoke(null, new object[] { 5 });
    }
    catch (TargetInvocationException e)
    {
        throw e.InnerException;
    }
}

选项 2:

void DoDynamicCall()
{
    MethodInfo method = /*referencing MyClass method void MyStaticFunction(int x)*/;
    method.Invoke(null, new object[] { 5 });
}

我真正想要的是让调用者DoDynamicCall接收异常,就好像他们调用了这个:

void DoDynamicCall()
{
    MyClass.MyStaticFunction(5);
}

有没有办法同时获得选项 1选项 2的好处?

编辑:

我希望拥有的选项(rethrow当场发明了特殊的新 C# 关键字):

void DoDynamicCall()
{
    MethodInfo method = /*referencing MyClass method void MyStaticFunction(int x)*/;
    try
    {
        method.Invoke(null, new object[] { 5 });
    }
    catch (TargetInvocationException e)
    {
        //Magic "rethrow" keyword passes this exception
        //onward unchanged, rather than "throw" which
        //modifies the StackTrace, among other things
        rethrow e.InnerException;
    }
}

这也将消除对这个怪人的需要,因为您可以rethrow e;改用:

try { ... }
catch (Exception e)
{
    if (...)
        throw;
}

一般来说,这将是一种与throw;“我必须直接在一个 catch 块中”的要求脱钩的方法。

4

4 回答 4

10

这是我想出的解决方案。它完成了工作。我仍然对其他答案感兴趣,因为可能会有更简单或更清洁的东西。

  • 当您想要的功能throw;但要传递的异常不是当前catch块的异常时,请使用throw Functional.Rethrow(e);
  • 替换try...catch...Functional.TryCatch
  • 替换try...catch...finally...Functional.TryCatchFinally

这是代码:

//Need a dummy type that is throwable and can hold an Exception
public sealed class RethrowException : Exception
{
    public RethrowException(Exception inner) : base(null, inner) { }
}

public static Functional
{    
    public static Exception Rethrow(Exception e)
    {
        return new RethrowException(e);
    }

    public static void TryCatch(Action _try, Action<Exception> _catch)
    {
        try { _try(); }
        catch (RethrowException e) { _catch(e.InnerException); }
        catch (Exception e) { _catch(e); }
    }

    public static T TryCatch<T>(Func<T> _try, Func<Exception, T> _catch)
    {
        try { return _try(); }
        catch (RethrowException e) { return _catch(e.InnerException); }
        catch (Exception e) { return _catch(e); }
    }

    public static void TryCatchFinally(
        Action _try, Action<Exception> _catch, Action _finally)
    {
        try { _try(); }
        catch (RethrowException e) { _catch(e.InnerException); }
        catch (Exception e) { _catch(e); }
        finally { _finally(); }
    }

    public static T TryCatchFinally<T>(
        Func<T> _try, Func<Exception, T> _catch, Action _finally)
    {
        try { return _try(); }
        catch (RethrowException e) { return _catch(e.InnerException); }
        catch (Exception e) { return _catch(e); }
        finally { _finally(); }
    }
}

更新

在 .NET 4.5 中有新的System.Runtime.ExceptionServices.ExceptionDispatchInfo。这可用于捕获异常:

var capturedException = ExceptionDispatchInfo.Capture(e);

然后稍后这用于恢复抛出异常:

capturedException.Throw();
于 2013-03-28T01:27:48.713 回答
1

不,我不相信有一种方法可以同时兼顾两者。但是, throwinge.InnerException仍然允许您获取原始堆栈跟踪,因为您可以简单地使用e.InnerException.StackTrace来获取原始堆栈跟踪。因此,简而言之,您应该使用选项 1

于 2013-03-27T20:06:52.973 回答
0

最好的选择是选项 3:根本不使用反射,而是使用Expression<T>.Compile().

而不是这样做:

static void CallMethodWithReflection(MethodInfo method)
{
    try
    {
        method.Invoke(null, new object[0]);
    }
    catch (TargetInvocationException exp)
    {
        throw exp.InnerException;
    }
}

尝试以此为目标:

private static void CallMethodWithExpressionCompile(MethodInfo method)
{
    Expression.Lambda<Action>(Expression.Call(method)).Compile()();
}

需要注意的是,您需要知道方法签名,尽管您可以编写动态构建表达式以适应多个签名之一的代码。

您可能并不总是能够使用这种技术,但是当您这样做时,它是最好的选择。出于所有意图和目的,它就像调用任何其他委托一样。如果您进行多次调用(在这种情况下只编译一次并保留已编译委托的句柄),它也比反射更快。

于 2014-04-29T07:45:22.787 回答
0

我有一个类似的问题,并想出了这个:

/// <summary>
/// Attempts to throw the inner exception of the TargetInvocationException
/// </summary>
/// <param name="ex"></param>
[DebuggerHidden]
private static void ThrowInnerException(TargetInvocationException ex)
{
    if (ex.InnerException == null) { throw new NullReferenceException("TargetInvocationException did not contain an InnerException", ex); }

    Exception exception = null;
    try
    {
        //Assume typed Exception has "new (String message, Exception innerException)" signature
        exception = (Exception) Activator.CreateInstance(ex.InnerException.GetType(), ex.InnerException.Message, ex.InnerException);
    }
    catch
    {
        //Constructor doesn't have the right constructor, eat the error and throw the inner exception below
    }

    if (exception == null ||
        exception.InnerException == null ||
        ex.InnerException.Message != exception.Message)
    {
        // Wasn't able to correctly create the new Exception.  Fall back to just throwing the inner exception
        throw ex.InnerException;
    }
    throw exception;
}

它的使用示例如下:

try
{
    return typeof(MyType).GetMethod(methodName, BindingFlags.Public | BindingFlags.Static)
                                    .MakeGenericMethod(new[] { myType) })
                                    .Invoke(null, parameters);
}
catch (TargetInvocationException ex)
{
    ThrowInnerException(ex);
    throw new Exception("Throw InnerException didn't throw exception");
}
于 2014-05-28T14:48:01.663 回答