7

Following up on my question yesterday to deepcopy an object with events in C# and attach the events of the original object to the Cloned copy is pretty easy, you just set the Event declaration in the Copy = the value in the original. Deep Clone when events are attached

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

I was hoping maybe there was something with reflection where you can examine what events are bound and somehow transfer those to the new object.

Community
  • 1
  • 1
Paul Farry
  • 4,730
  • 2
  • 35
  • 61

1 Answers1

5

yes you can, and its not that difficult, but it seems there isint a whole lot of info on this, so great 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

jasper
  • 3,424
  • 1
  • 25
  • 46
  • Do you know if this works with asp.net? I've had no luck with .GetField("SomeEvent"), it always returns Nothing. – mrmillsy Dec 17 '14 at 15:15
  • I believe this ALMOST works with asp.net with code-behind. As the code-behind partial class is inherited into the final output page, you need to call `Me.GetType.BaseType`. Maybe this comment will be useful for someone. – mrmillsy Dec 18 '14 at 11:56