1

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

'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}}

伟大的!现在我有了这本字典,我可以将字符串类型的事件流转换为 I'm- a-real-boy事件!我什至想出了如何称呼它们:

 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
4

1 回答 1

3

听起来一层间接性会在这里为您提供帮助。不是直接将字符串映射到事件,而是将字符串映射到将引发事件的操作,如下所示:

Private mapping As New Dictionary(Of String, Action) From _
    {{"happened", Sub() RaiseEvent ItHappened()},
     {"almostHappened", Sub() RaiseEvent ItAlmostHappened()}}
于 2013-05-22T14:54:19.133 回答