如何捕获使用 MethodInfo.Invoke 调用的方法中抛出的异常?

Set*_*o N 3 c# reflection exception try-catch invoke

我有以下代码:

using System;
using System.Reflection;

namespace TestInvoke
{
  class Program
  {
    static void Main( string[] args )
    {
      Method1();
      Console.WriteLine();
      Method2();
    }

    static void Method1()
    {
      try
      {
        MyClass m = new MyClass();
        m.MyMethod( -3 );
      }
      catch ( Exception e )
      {
        Console.WriteLine( e.Message );
      }
    }

    static void Method2()
    {
      try
      {
        string className = "TestInvoke.MyClass";
        string methodName = "MyMethod";
        Assembly assembly = Assembly.GetEntryAssembly();
        object myObject = assembly.CreateInstance( className );
        MethodInfo methodInfo = myObject.GetType().GetMethod( methodName );
        methodInfo.Invoke( myObject, new object[] { -3 } );
      }
      catch ( Exception e )
      {
        Console.WriteLine( e.Message );
      }

    }
  }

  public class MyClass
  {
    public void MyMethod( int x )
    {
      if ( x < 0 )
        throw new ApplicationException( "Invalid argument " + x );

      // do something
    }

  }
}
Run Code Online (Sandbox Code Playgroud)

方法1方法2都执行MyClass.MyMethod,但方法一输出:

Invalid argument -3
Run Code Online (Sandbox Code Playgroud)

Method2输出:

Exception has been thrown by the target of an invocation.
Run Code Online (Sandbox Code Playgroud)

我们可以修改Method2以便它可以像Method1一样捕获异常吗?

小智 5

看一看InnerException。在 .NET 中,反射将包装异常 - 这对于了解异常是如何调用的很有用。请参阅内部异常属性具有您正在寻找的异常。 堆栈跟踪

因此,要获得相同的异常,只需调用即可Console.WriteLine(e.InnerException.Message)