You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过反射或其他技术获取VB中Handles绑定的事件名称?

获取VB.NET中Handles绑定的事件名称

直接用常规反射拿不到Handles绑定的事件名称——因为VB编译器会把Handles语法编译成IL里的AddHandler调用,运行时不会保留原绑定的元数据。但可以通过以下两种方式获取:

  • 读取程序集元数据:用System.Reflection.Metadata或者第三方库(比如Mono.Cecil)解析程序集的元数据,VB编译器会给带Handles的方法添加HandlerAttribute,里面存着绑定的事件信息。
    举个Mono.Cecil的示例代码:

    ' 先引用Mono.Cecil NuGet包
    Dim assembly = AssemblyDefinition.ReadAssembly("你的程序集路径.dll")
    Dim targetType = assembly.MainModule.Types.First(Function(t) t.Name = "目标类名")
    For Each method In targetType.Methods
        If method.HasCustomAttributes Then
            Dim handlerAttr = method.CustomAttributes.FirstOrDefault(Function(a) 
                a.AttributeType.Name = "HandlerAttribute"
            End Function)
            If handlerAttr IsNot Nothing Then
                Dim eventName = handlerAttr.ConstructorArguments(0).Value.ToString()
                Console.WriteLine($"方法 {method.Name} 绑定了事件 {eventName}")
            End If
        End If
    Next
    
  • Roslyn分析器:如果是在编译阶段获取,可以写一个Roslyn自定义分析器,直接解析VB代码语法树,提取Handles子句里的事件名称,适合批量处理代码的场景。

内容的提问来源于stack exchange,提问作者gegy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 16:04:52