【问题标题】:Storing events in a dictionary, and then raising them将事件存储在字典中,然后引发它们
【发布时间】:2013-05-21 22:38:37
【问题描述】:

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

'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

【问题讨论】:

  • 这是出于好奇心的练习,还是您想要解决的问题?
  • 请提供我们可以复制的真实代码。
  • 使用Custom keyword 定义自定义事件。使用访问器更新目录。
  • @HansPassant,每次我想创建自己的自定义事件时,我真的需要所有这些代码吗?这让我想改变这个类以便能够RegisterCommand(commandName As String, handler As Action) ;)

标签: .net vb.net events dictionary


【解决方案1】:

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

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

【讨论】:

  • 啊,好多了!一个额外的层有时可以做的事情令人惊讶:)
猜你喜欢
  • 1970-01-01
  • 2015-06-05
  • 1970-01-01
  • 1970-01-01
  • 2016-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多