我有一个 asp.net 网页。这是实现页面的类:
public partial class _Default : System.Web.UI.Page
{
private readonly string delegateName = "DynamicHandler";
protected void Page_Load(object sender, EventArgs e)
{
EventInfo evClick = btnTest.GetType().GetEvent("Click");
Type tDelegate = evClick.EventHandlerType;
MethodInfo method = this.GetType().GetMethod("DynamicHandler",
BindingFlags.NonPublic | BindingFlags.Instance);
Delegate d = Delegate.CreateDelegate(tDelegate, this, method);
MethodInfo addHandler = evClick.GetAddMethod();
Object[] addHandlerArgs = { d };
addHandler.Invoke(btnTest, addHandlerArgs);
}
private void DynamicHandler(object sender, EventArgs e)
{
throw new NotImplementedException();
}
}
我正在尝试动态连接事件处理程序。出于某种原因,method
仍然为空,我不知道为什么。我以前做过很多次,但我不知道我错过了什么。
编辑:我发现 this.GetType()
返回页面 ASP.default_aspx
的类型,而不是实现页。我真的不知道如何解决这个问题......
最佳答案
为了其他人的利益,如果您传递的参数与您尝试查找的方法的参数不匹配,GetMethod()
也可以返回 null。因此,例如,如果您正在尝试查找方法:
SomeMethod(int intParam, string stringParam)
您需要将参数类型传递给GetMethod
:
type.GetMethod("SomeMethod", new[] { typeof(int), typeof(string) });
或者,如果你想指定特殊的绑定(bind)标志:
type.GetMethod("SomeMethod", BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { typeof(int), typeof(string) }, null);
关于c# - GetMethod 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18569001/