.net - 我可以在 .NET 中重定向事件吗?

标签 .net events

我有一个类正在捕捉 System.Diagnostics.DataReceivedEventArgs事件。

我想让此事件在外部可用。为了实现这一目标 目前我正在内部捕捉到这个并引发另一个事件,这对我来说似乎有点重复。

最好的方法是什么?我可以连接这些事件,这样我就不需要引发新事件吗?

这是代码:

Class MyClass  

Public Event OutputDataReceived(sender As Object, e As System.Diagnostics.DataReceivedEventArgs)

Public Sub Action()
    ....
     AddHandler Process.OutputDataReceived, AddressOf ReadData
    ....
End Sub

  Private Sub ReadData(ByVal sender As Object, ByVal e As System.Diagnostics.DataReceivedEventArgs)
        RaiseEvent Me.OutputDataReceived(sender, e)
    End Sub

End Class

最佳答案

“捕捉”事件是什么意思?您可以做的一件事是公开您自己的事件,该事件仅将订阅/取消订阅传递给另一个事件:

public event DataReceivedEventHandler DataReceived
{
    add
    {
        realEventSource.DataReceived += value;
    }
    remove
    {
        realEventSource.DataReceived -= value;
    }
}

有关事件的更多详细信息,请阅读 my article on the topic - 如果有任何不清楚的地方请告诉我。

编辑:这是 VB.NET 中的等效内容:

Public Custom Event DataReceived As DataReceivedEventHandler
    AddHandler(ByVal value As DataReceivedEventHandler)
        AddHandler Me.realEventSource.DataReceived, value
    End AddHandler
    RemoveHandler(ByVal value As DataReceivedEventHandler)
        RemoveHandler Me.realEventSource.DataReceived, value
    End RemoveHandler
    RaiseEvent(ByVal sender as Object, ByVal args as DataReceivedEventArgs)
        Throw New NotSupportedException
    End RaiseEvent
End Event

关于.net - 我可以在 .NET 中重定向事件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/579676/

相关文章:

java - 不会继续执行 ACTION_DOWN 上的语句

c# - .net cf TextBox 显示键盘焦点

.net - 使用 Newtonsoft.Json,如何将 JSON 反序列化为具有包含接口(interface)类型的 IEnumerable 属性的类型?

.net - DependencyProperty VS 无冗余状态管理

java - 按下键时 GWT onPreviewNativeEvent 运行 2 次

javascript - Kendo Draggable - 从拖动事件处理程序中暂时暂停拖动

.net - 语法高亮 : rich text box control for . NET

c# - ping 子网时程序锁定

javascript - $ ("#id option").click(function(){ }) 不适用于 safari 或 chrome?

javascript - 将事件绑定(bind)到动态创建的元素