简体   繁体   中英

C# Custom Copy constructor, copy events

I'm trying to create a copy constructor for my C# object using reflection. I am able to copy all of the fields and properties (those are easy) but I'm having some issues copying the Events.

Is there a way to (via reflection) copy all of the delegates that have subscribed to an event from one object to another? (Both will be the same type)

Thank you :)

It will entirely depend on the implementation. After all, an event can be implemented any way you want. If you're using a field-like event then you should be able to just copy the field value:

using System;

class Test
{
    public event EventHandler SomeEvent;

    public Test(Test other)
    {
        this.SomeEvent = other.SomeEvent;
    }
}

This is fine as delegates are immutable - subscribing to an event creates a new delegate and assigns that to the field, so your two objects would be independent. If the event was implemented using something like EventHandlerList you would want to create a clone rather than using simple field assignment.

EDIT: To do this with reflection, you'd simply use the fields like any other. Field-like events are simply events backed by fields. If you're already copying all the fields within a class, you won't have any extra work to do.

Be aware that unless you go to extra effort, you'll only make 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 to the list will be seen via both objects.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM