我以前见过用户解决这个问题,比如在线程中: C#very dynamic invocation
但是我对给出的代码没有太大的成功。我基本上是在尝试使用一些变量字符串来调用方法。
这是我到目前为止所拥有的。
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
public partial class _Model : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string TargetMethod = "Index";
Type t = System.Type.GetType("_Model");
System.Reflection.MethodInfo methodInfo = t.GetMethod(TargetMethod);
methodInfo.Invoke(t, new object[] {});
}
protected void Index(){
Response.Write("Index: Dynamically called!");
}
}
在视图页面上,我应该看到字符串“索引:动态调用!” 写入屏幕但我收到错误:
异常详细信息:System.NullReferenceException:对象引用未设置为对象的实例。
请帮忙,谢谢。