![](/img/trans.png)
[英]How to get a parameter value passed as a reference with MethodInfo.Invoke when throws an exception in the invoked method
[英]How to catch Exception thrown in a method invoked by using MethodInfo.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
}
}
}
方法1和方法2都執行MyClass.MyMethod,但方法一輸出:
Invalid argument -3
而Method2輸出:
Exception has been thrown by the target of an invocation.
我們可以修改Method2以便它可以像Method1一樣捕獲異常嗎?
看一下InnerException
。 在.NET中,反射將包裝異常-這對於了解異常的調用方式很有用。 請參閱內部異常屬性具有您要查找的異常。
因此,要具有相同的異常,只需調用Console.WriteLine(e.InnerException.Message)
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.