2
I는 다음과 같은 코드가 :MethodInfo.Invoke를 사용하여 호출 한 메서드에서 Throw 된 Exception을 catch하는 방법?
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
}
}
}
방법 항목 및 모두 가을 MyClass.MyMethod 실행 방법 2하지만 방법 항목 출력 :
Invalid argument -3
동안 방법 2 출력 :
을Exception has been thrown by the target of an invocation.
2 방법 2을 수정할 수 있으므로 방법 1에서 예외를 catch 할 수 있습니까?