Can I redirect events in .NET?

I have a class that catches an event System.Diagnostics.DataReceivedEventArgs.

I want to make this event accessible from the outside. For this, I am currently breaking it internally and raising another event that seems a little duplicate to me.

What is the best way to do this? Can I connect these events, so I don’t need to raise a new event?

Here is the code:

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
+3
source share
1 answer

What do you mean by catching an event? One thing you can do is expose your own event, which simply passes the subscriptions / unsubscriptions to another:

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

- , - .

EDIT: 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
+8

Source: https://habr.com/ru/post/1703697/


All Articles