Question

I would like to know how it is best done to clone an object and reattach the event subscribers to the newly cloned object.

Background: I use a Converter, which can convert from a string to an object. The object is known in the context of the converter, so I just want to take that object and copy the property values and the event invocation 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's assume I have access to the source
        // object by using the object named "Original":

        Copied.Updated += Original.???
    }

    return Copied;
}

So is there a possibility, when I have access to the source object, to attach its subscribers to the copied objects event?

Regards, Greg

Was it helpful?

Solution

Well you can define a function in Original class that gives you the event handlers.

Original Class:

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 your converter:

Copied.Event = Original.GetInvocationList();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top