C # Custom Copy constructor, copying events

I am trying to create a copy constructor for my C # object using reflection. I can copy all fields and properties (this is easy), but I am having some problems copying events.

Is there a way (through reflection) to copy all the delegates who subscribe to the event from one object to another? (Both will be the same type)

Thanks:)

+4
source share
1 answer

This will be entirely implementation dependent. In the end, an event can be implemented in any way. If you are using a field event, you should simply copy the value of the field:

using System; class Test { public event EventHandler SomeEvent; public Test(Test other) { this.SomeEvent = other.SomeEvent; } } 

This is great because the delegates are immutable - subscribing to an event creates a new delegate and assigns this field, so your two objects will be independent. If the event was implemented using an EventHandlerList , you would like to create a clone, not a simple field assignment.

EDIT: To do this with reflection, you simply use the fields like any others. Field events are simply events supported by fields. If you already copy all the fields inside the class, you will not have any additional work.

Remember that if you do not make additional efforts, you will make only a shallow copy - for example, if you have a field of type List<string> , your new object will refer to the same object as the old object, so any changes in the list will be visible through both objects.

+2
source

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


All Articles