111,086
社区成员




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectionTestDll
{
public class Class1
{
public Class1()
{
}
public string MethodErr2(string pValues, string pValues1)
{
throw new Exception("MethodErr2 " + pValues + pValues1);
}
}
}
private void btnMethodErr2_Click(object sender, EventArgs e)
{
try
{
Assembly t = Assembly.Load("ReflectionTestDll");
Type a = t.GetType("ReflectionTestDll.Class1");
string[] bb = new string[] { "aaaa", "bbbbb" };
object obj = Activator.CreateInstance(a, bb);
MethodInfo mi = a.GetMethod("MethodErr2");
object[] aa = new string[] { "For Err ", "Method2" };
string s = (string)mi.Invoke(obj, aa); //带参数方法的调用
}
catch (Exception Ex)
{
//我希望这里能够获得异常,可是每次都是“调用的目标发生了异常”
}
this.txtMSG.Text = mSB.ToString();
}
void fn(int n)
{
if (n >= 10)
return;
throw new ArgumentException("参数必须大于10");
}
Type type = typeof(Program);
object instance = Activator.CreateInstance(type);
MethodInfo mi = type.GetMethod("fn", BindingFlags.NonPublic | BindingFlags.Instance);
try
{
mi.Invoke(instance, new object[] { null });
}
catch(TargetInvocationException targetEx)
{
if (targetEx.InnerException != null)
{
throw targetEx.InnerException;
}
}