将事件存储在字典中,然后提升它们

时间:2013-05-21 22:38:38

标签: .net vb.net events dictionary

我设法获得了一个可以存储事件的字典:

'Terrible .NET events... where's sender and e?!
Public Event ItHappened()
Public Event ItAlmostHappened()

Private mapping As New Dictionary(Of String, System.Delegate) From _
    {{"happened", ItHappenedEvent},
     {"almostHappened", ItAlmostHappenedEvent}}

大!现在我有这个字典,我可以将一个字符串类型的事件流转换为我是一个真实的男孩事件!我甚至想出了如何打电话给他们:

 mapping(key).DynamicInvoke()

但是,即使在为事件添加处理程序之后,唉mapping(key)也为空。如果我在添加处理程序后将字典中的值更新为mapping("happened") = ItHappenedEvent,那么一切都很好。有没有办法以编程方式完成类似的事情?或以其他方式存储字符串 - >事件映射将字符串输入转换为运行时的事件?

修改

按要求提供实际代码。这是允许我们将命令传递给服务器上运行的WinService的机制的一部分。 “做你能做的最简单的事情”方法引导我们使用服务器上的文件作为信号机制。

Public Class CommandChecker
  Implements IDisposable

  Public Event RefreshPlannableStations()

  Private _knownCommmands As New Dictionary(Of String, System.Delegate) From _
    {{"refreshStations", RefreshPlannableStationsEvent}}

  Private WithEvents _fsw As FileSystemWatcher

  Public Sub New(ByVal path As String)
    Me._fsw = New FileSystemWatcher(path, "*.command")
  End Sub

  Private Sub fsw_Created(ByVal sender As Object,
                          ByVal e As FileSystemEventArgs) Handles _fsw.Created
    If Me._knownCommmands.ContainsKey(key) Then
      Me._knownCommmands(key).DynamicInvoke()
      'Delete file to acknowledge command
    EndIf
  End Sub

  'Snipped IDisposable stuff
End Class

在其他地方,我们创建这个类,然后订阅它的事件。

Me._checker = New CommandChecker()
AddHandler Me._checker.RefreshPlannableStations, AddressOf OnRefreshStations

1 个答案:

答案 0 :(得分:3)

听起来像一层间接会帮助你。不是直接将字符串映射到事件,而是将字符串映射到将引发事件的操作,如下所示:

Private mapping As New Dictionary(Of String, Action) From _
    {{"happened", Sub() RaiseEvent ItHappened()},
     {"almostHappened", Sub() RaiseEvent ItAlmostHappened()}}