asp.net - 使用带有代码隐藏的网络表单通过反射引发事件

标签 asp.net .net vb.net events reflection

我意识到有很多问题都涉及通过反射引发事件,但是我无法找到以下问题的答案 [我怀疑答案是“否”]:

给定事件的“标准”声明,是否有任何方法可以通过引用字符串文字来引发事件。

例如伪代码:

Dim eventName As String = "TestEvent"
RaiseEvent eventName

显然那是行不通的。

我可以获得事件处理程序/多播委托(delegate)的类型

Me.GetType.GetEvent("TestEvent").GetAddMethod.GetParameters(0).Name
// "TestEventEventHandler

但是我在页面对象上找不到this的实例来调用.GetInvocationList

这类似于这个问题:How can I get an actual EventHandler delegate instance from an event in VB.NET?

但是在这里,我特别关注从字符串引发事件。

编辑:

vb.net/webforms 环境中有一些不同之处。根据我对已接受答案的评论,由于(我相信)代码隐藏模型的性质,不可能从 Me.GetType() 返回与事件对应的字段,因为在运行时 Me 指的是 .aspx 文件中的继承类,而不是 .aspx.vb 文件中的类。

实际上这意味着我必须使用 Me.BaseType.GetType() 来查找该字段。

第二个不同之处在于,虽然与最终答案无关,但在 c# 中您可以直接引用事件处理程序 MulticastDelegate,而在 vb.net 中您不能 - 或者至少不能这样做必须使用 intellisense 不支持的未记录的功能,如:How can I get an actual EventHandler delegate instance from an event in VB.NET?

最佳答案

您可以调用GetField在您的类型实例上,然后继续调用 GetValue()在返回的 FieldInfo 上。这是一个示例(在 c# 中,因为我不会说 vb.net)

class Foo
{
    public event EventHandler Bar;

}
class Program
{
    static void Main(string[] args)
    {
        var foo = new Foo();
        foo.Bar += FooOnBar;

        var ev = (MulticastDelegate)foo.GetType().GetField("Bar", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(foo);
        if (ev != null)
        {
            foreach (var del in ev.GetInvocationList())
            {
                del.Method.Invoke(del.Target, new object[] {foo, new EventArgs()});
            }
        }
        Console.ReadLine();
    }

    private static void FooOnBar(object sender, EventArgs eventArgs)
    {
        Console.WriteLine("Invoked!");
    }
}

关于asp.net - 使用带有代码隐藏的网络表单通过反射引发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27528115/

相关文章:

asp.net - 从 Web 应用程序生成 XPS 文档

c# - 如何在 HttpContext 中正确设置 session ?

.net - 远程 MSMQ、事务和 ReceiveById 失败 - "Message requested was not found in the queue specified"

vb.net - 全局变量的值不会改变

vb.net - 在 VB.NET 中创建 DLL 文件并在 Excel VBA 中使用

c# - 无法在 javascript 中获取 html 文本框的值

.net - 尝试以编程方式连接到 TFS 2010 时出现权限错误

c# - 带整数表达式的 switch case

vb.net - Windows 窗体 - 如何通过列名称访问 ListView 的子项?

java - 在 asp.net (c#) 和 android (java) 中共享业务逻辑