How to attach events of an original object to a deeply copied clone

Following my question yesterday about making an event object in C # and attaching the events of the original object to the cloned copy, you simply set the event declaration to Copy = the value in the original. Deep clone when connected to events

How do you do this in VB.Net? (Using .Net 2)

I was hoping there might have been something with reflection where you can check which events are related and somehow pass them on to a new object.

+5
source share
1 answer

Yes, you can, and it’s not so difficult, but it seems that there is a lot of information about it, so the big question.


Dim sourceObject As New FooBar
Dim destObject As New FooBar

AddHandler sourceObject.SomeEvent, AddressOf myFunc


Dim miHandler As FieldInfo = GetType(FooBar).GetField("SomeEvent", BindingFlags.Static Or BindingFlags.NonPublic Or BindingFlags.Instance)
Dim sourceDelegate As [Delegate] = miHandler.GetValue(sourceObject)

Dim addDelegate As [Delegate] = sourceDelegate.GetInvocationList().First() ' if its multicast, then you'll need to copy the lot

AddHandler destObject.SomeEvent, addDelegate

+4

All Articles