c# - GetMethod 返回 null

标签 c# asp.net reflection

我有一个 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/

相关文章:

c# - 在旧版 “aspx” 项目中包含 Azure AD 身份验证

c# - WebSocket WCF 传输绑定(bind)

c# - 当参数发生异常时重定向

c# - 使用 EPPlus 将 PrintArea 设置为 "Print Entire Workbook"

VS 2013 RC 中缺少 ASP.NET Web 窗体脚手架功能

scala - scala.mobile 应该完成什么任务?

python - 如何测试一个类是否包含特定属性?

c# - Expression.Bind() - 它实际上做了什么?

c# - 创建邮件时在 Outlook 加载项 (C#) 中读取 Outlook 附件内容

c# - Entity Framework - 1 到 ... 太多到 1 选择