private void button1_Click(object sender, System.EventArgs e)
{
object[] methodArgs = {"test",10.2};
try
{
object s = typeof(MainForm).InvokeMember("test",BindingFlags.InvokeMethod,null,new MainForm(),methodArgs);
MessageBox.Show(s.ToString());
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
public string test(string a,double b)
{
return a+"double:"+b.ToString();
}
public string test(string a,int b)
{
return a+"int:"+b.ToString();
}
public string test(string a,int b)
{
return a+"int:"+b.ToString();
}

博客展示了一段C#代码,在button1的点击事件中,通过反射调用MainForm类的test方法,传入参数并尝试执行。若执行成功,显示返回结果;若出现异常,则捕获并显示异常信息。代码还定义了多个重载的test方法。

被折叠的 条评论
为什么被折叠?



