Cloning Event Subscribers

I would like to know what is the best way to clone an object and attach event subscribers to the newly cloned object.

Background: I use a converter that can convert from string to object. The object is known in the context of the converter, so I just want to take this object and copy the property values ​​and event call lists:

[TypeConverter(typeof(MyConverter))]
class MyObject 
{
    public string prop1 { get; set; }
    public string prop2 { get; set; }
    public delegate void UpdateHandler(MyObject sender);
    public event UpdateHandler Updated;
}

class MyConverter(...) : ExpandableObjectConverter
{
    public override bool CanConvertFrom(...)
    public override object ConvertFrom(...) 
    {
        MyObject Copied = new MyObject();   
        Copied.prop1 = (value as string);
        Copied.prop2 = (value as string);

        // For easier understanding, let assume I have access to the source
        // object by using the object named "Original":

        Copied.Updated += Original.???
    }

    return Copied;
}

So, is it possible, when I have access to the source object, to attach its subscribers to the event of the copied objects?

Regards, Greg

+3
source share
1 answer

Well, you can define a function in the original classthat gives you handlers event.

Original Grade:

class A
{
    public event EventHandler Event;

    public void Fire()
    {
        if (this.Event != null)
        {
            this.Event(this, new EventArgs());
        }
    }

    public EventHandler GetInvocationList()
    {
        return this.Event;
    }
}

And then call the following from the converter:

Copied.Event = Original.GetInvocationList();
+3

All Articles