Problem:
I often find that I want to handle an event in a collection of objects. As objects are added and removed from the collection, each object must be connected or detached. I find it tedious and repeated to develop each class that does this with the same connection code.
Desired solution: So, I'm trying to come up with something like EventBindingListthat contains removable objects and allows the user to simultaneously connect several objects at once, as well as add and remove objects in the list.
To keep it common, you must use Reflection. In the list constructor, the user can specify EventInfo, or by the name of the event, which event is connected. It seemed the easiest way.
private EventInfo _info;
public EventBindingList(string EventName)
{
_info = typeof(T).GetEvents().Where(e => e.Name == EventName).First();
}
public EventBindingList(EventInfo info)
{
_info = info;
}
I tried several approaches, but I'm still having problems with the differences between methods, delegates, lambdas and EventHandlers.
Bad Solution 1:
One of my solutions that didn’t work was to use a special accessory of events. This will be an event in the list containing the objects to be connected. This is due to the fact that when adding an EventHandler, an ArgumentException is thrown: Object of type 'System.EventHandler' cannot be converted to type 'ExternalProject.CustomEventHandler'.I tried to give the EventHandler the correct type (using universal type arguments, since this is an external project event handler), but the cast did not work.
public event EventHandler ElementEvent
{
add
{
_handlers.Add(value);
foreach (T t in this)
{
_info.AddEventHandler(t, value);
}
}
remove
{
foreach (T t in this)
{
_info.RemoveEventHandler(t, value);
}
_handlers.Remove(value);
}
}
Bad Solution 2:
, , . , . .
:
- , ?