在VB.NET中是否可以轻松编写一个事件处理程序来处理每个触发的事件?我想知道是否可以使用这样的东西制作日志记录系统. 我想做一些像(在伪代码中)的东西: Public Sub eventHandledEvent
我想做一些像(在伪代码中)的东西:
Public Sub eventHandledEvent(ByVal sender As Object, ByVal e As EventArgs) File.Write(sender.EventName) End Sub
我意识到它会很慢,但它不适用于生产系统,只能作为开发工具.
你可以用 reflection做到这一点.这是怎么做的.使用名为TextBox1的文本框创建表单.粘贴以下代码.运行项目并查看即时窗口.Public Class Form1 Private Sub Form1_Activated(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Activated RegisterAllEvents(TextBox1, "MyEventHandler") End Sub Sub MyEventHandler(ByVal sender As Object, ByVal e As EventArgs) Debug.WriteLine("An event has fired: sender= " & sender.ToString & ", e=" & e.ToString) End Sub Sub RegisterAllEvents(ByVal obj As Object, ByVal methodName As String) 'List all events through reflection' For Each ei As System.Reflection.EventInfo In obj.GetType().GetEvents() Dim handlerType As Type = ei.EventHandlerType Dim method As System.Reflection.MethodInfo = Me.GetType().GetMethod(methodName) 'Create a delegate pointing to the method' Dim handler As [Delegate] = [Delegate].CreateDelegate(handlerType, Me, method) 'Register the event through reflection' ei.AddEventHandler(obj, handler) Next End Sub End Class
这是来自Francesco Balena的书Programming Microsoft Visual Basic 2005 The Language.the techique适用于任何引发事件的对象,而不仅仅是控件.它使用contravariance.
如果你是buy the book,那么有一个完整的解释和一些代码,它们将允许你识别在通用处理程序中触发了哪个事件,并使用正则表达式来处理事件的子集.我觉得我不能在这里发布这么长的摘录.