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
Hello
I am developing a utility to be reused in other programs. It
I have an object of type Control (a TextBox, ComboBox, etc.) that other
programmers use it in applications. they may set some of properties or
assign event handlers. I need to be able to clone the manipulated
control at runtime.
I could use the Clone method of some objects (like Font, Style, String,
etc..) but the controls like Button, TextBox, ListBox doesn't have this
kind
of method.
How can I create a clone of an object instance for controls like
TextBox,
ListBox, ListViews, CheckBox ??
Any help is appreciated,