通过反射调用方法而未获取TargetInvocationException

jga*_*fin 4 c# reflection

我找到了一种使用反射的方法(并得到了它MethodInfo)。如何在不TargetInvocationException引发异常的情况下调用它?

更新资料

我正在创建一个命令实现,其中命令由实现的类处理

public interface ICommandHandler<T> where T : class, ICommand
{
    public void Invoke(T command);
}
Run Code Online (Sandbox Code Playgroud)

由于有一个调度程序负责查找并将所有处理程序映射到正确的命令,因此我无法直接调用方法,而只能使用反射。就像是:

var handlerType = tyepof(IHandlerOf<>).MakeGenericType(command.GetType());
var method = handlerType.GetMethod("Invoke", new [] { command.GetType() });
method.Invoke(theHandler, new object[]{command});
Run Code Online (Sandbox Code Playgroud)

它工作正常,但我希望所有异常都传递给调用命令的代码。

使调用者可以使用:

try
{
    _dispatcher.Invoke(new CreateUser("Jonas", "Gauffin"));
}
catch (SomeSpecificException err)
{
    //handle it.
}
Run Code Online (Sandbox Code Playgroud)

而不是必须抓住TargetInvocationException

(我知道我可以抛出内部异常,但是由于堆栈跟踪已被破坏,这是毫无价值的)

更新2

是一个可能的解决方案。

但这似乎更像是一种黑客。没有更好的解决方案吗?也许带有表情之类的东西?

Ani*_*Ani 5

Delegate从中创建MethodInfo(通过的重载之一Delegate.CreateDelegate),然后调用。这不会将方法抛出的任何异常包装在TargetInvocationExceptionMethodInfo.Invoke中。

class Foo
{
    static void ThrowingMethod()
    {
        throw new NotImplementedException();
    }

    static MethodInfo GetMethodInfo()
    {
        return typeof(Foo)
                .GetMethod("ThrowingMethod", BindingFlags.NonPublic | BindingFlags.Static);
    }

    // Will throw a NotImplementedException
    static void DelegateWay()
    {
        Action action = (Action)Delegate.CreateDelegate
                                    (typeof(Action), GetMethodInfo());
        action();
    }

    // Will throw a TargetInvocationException 
    // wrapping a NotImplementedException
    static void MethodInfoWay()
    {
        GetMethodInfo().Invoke(null, null);
    }
}
Run Code Online (Sandbox Code Playgroud)

编辑

(正如OP所指出的,DynamicInvoke在这里也无法工作,因为它也可以包装)

根据您的更新,我只会使用dynamic

((dynamic)theHandler).Invoke(command);
Run Code Online (Sandbox Code Playgroud)