Z
Zürcher See
If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?
from my source object to the target "cloned" object?
If I want to implement an IClonable interface, how can I copy the events
from my source object to the target "cloned" object?
Mattias Sjogren said:class CloneableWithEvents : ICloneable
{
public event MyDelegate MyEvent;
public object Clone()
{
CloneableWithEvents clone = new CloneableWithEvents();
clone.MyEvent += MyEvent;
return clone;
}
}
wouldn't
CloneableWithEvents clone = (CloneableWithEvents)this.MemberwiseClone();
be simpler?
It catches private fields, including events(assuming they are
normal fields, not in a hash table or anything, and it will work when
overridden,
the above method breaks when you inherit from it.
Mattias Sjögren said:class CloneableWithEvents : ICloneable
{
public event MyDelegate MyEvent;
public object Clone()
{
CloneableWithEvents clone = new CloneableWithEvents();
clone.MyEvent += MyEvent;
return clone;
}
}
Mattias
control) I would strongly suggest you avoid MemberwiseClone. You don't
know if the derived data can be safely be copied like that, or if it
for example references some unmanaged resource.