H
Hamed
If I just could copy the events, this would be enough for me.
Nicholas Paldino said:Hamed,
Ultimately, you can't do it reliably.
If the method that is creating the clone is a member of the class being
cloned, then you can simply do:
// Inside clone method.
MyClass clone = new MyClass();
clone.MyEvent += this.MyEvent;
This assumes that you are declaring an event using the event keyword,
and not using add/remove handlers. It works because the C# compiler
creates a backing field of the same name (MyEvent).
However, if you declare your event like this:
private EventHandler myEventHandler;
public event EventHandler MyEvent
{
add
{
myEventHandler += value;
}
remove
{
myEventHandler -= value;
}
}
Then the call to assign the event will fail, because the compiler will
not see the backing field that has the delegate in it, and revert to that.
Even if you are making the call from outside the type, the same problem
exists, since there is nothing on the metadata that links the event to the
backing field. There is nothing in the metadata that says that the
backing field has to be connected to the event. It's like asking for
metadata on a property, and then asking what the backing field is (or
multiple backing fields, since properties can really return anything they
want, just like event handlers).
So, that being said, there really isn't a reliable way to do this. The
best you could do is have an interface (if you plan on doing this across
multiple types) which would return a mapping of events to handlers, and
then when you clone the object, you would get those delegates and then
perform the clone.
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)
Hamed said:Hello
It seems that I should implement ICloneable to implement my own clone
object. the critical point for me is to make a control object based on
another control object that all of its event handlers are set like the
old one. Is there a way to do this job?
For example, is there a way to use EventInfo object to get all event
handlers of the old control in runtime and set my new cloned control
events to the event handlers of the old control?
Any suggestion is appreciated.
Regards
Hamed
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.