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

时间:2009-02-23 22:35:39

标签: .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

1 个答案:

答案 0 :(得分:8)

“抓住”活动是什么意思?你可以做的一件事是公开你自己的事件,它只是将订阅/取消订阅传递给另一个:

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