3
我见过的用户线程之前解决这个问题,如: C# very dynamic invocation动态调用C#ASP.NET的方法
但我还没有与给定的代码很成功。我基本上试图调用一个使用一些变量字符串的方法。
这是我到目前为止。
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!");
}
}
在视图页上,我应该看到字符串“Index:Dynamically called!”写入屏幕,但我得到错误:
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
请帮助,谢谢。
仍然无法正常工作,因为Invoke的参数是错误的。它应该是'this'而不是't'。 – 2013-03-15 13:28:10
@BennorMcCarthy已经在编辑:) – 2013-03-15 13:28:43
他的代码还有另一个错误。应该是'methodInfo.Invoke(this,new object [] {})'; – hazzik 2013-03-15 13:29:00