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

3

我有以下代码:

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
    }

  }
}

Method1Method2 都执行了 MyClass.MyMethod,但是 Method1 输出:

Invalid argument -3

当使用 Method2 时,输出结果为:

Exception has been thrown by the target of an invocation.

我们能否修改 Method2 ,使其像 Method1 一样捕获异常?

1个回答

5

看一下InnerException。在.NET反射中,异常会被包装起来——这对于知道异常是如何被调用的很有用。可以看到内部异常属性拥有你要查找的异常。 stack trace

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接