I have these two lists:
List<IEvent> iEvent = new List<IEvent>();
List<IEventListener> listeners = new List<IEventListener>();
And I wanted to replace them with two dictionaries.
private Dictionary<IEvent, Action<EventInfo, Type, Property> eventSender;
private Dictionary<IEventListener,Action<EventInfo, Type, Property>> eventListerner;
This was the original function to add EventSenders:
public void AddSender(IEvent sender)
{
if (!iEvent.Contains(sender))
{
iEvent.Add(sender);
isEventAdded = true;
}
}
And I wanted to replace it with this because sometimes I am interested in knowing which object the event belongs to:
public void AddSender(IEvent sender)
{
eventSender.Add(sender, sender.OnEvent); //-->error
}
I have an error message telling me that "sender.OnEvent" can only go to the left of += or -=
Exactly the same thing happens to me with the function of adding Listeners
public void AddListener(IEventListener listener)
{
listeners.Add(listener);
foreach (IEvent sender in iEvent)
{
sender.OnEvent += listener.Listen;
}
}
Is there any way I can add "sender.OnEvent" in the dictionary?
Thank you very much!!
//------------------------------------------------ ---
UPDATE:
//------------------------------------------------ --
OnEven comes from this interface:
public interface IEvent
{
public event Action<EventInfo, EntityEvent.Type, EntityEvent.Property> OnEvent;
public void SendEvent(EventInfo sendInfo, EntityEvent.Type eventType, Property property);
}
//------------------------------------------------ ---
The problem has something to do with the interface or the class that implements it because I have declared the following within the same class where the AddListener() function is and it does not give me any error...
public event Action<EventInfo, EntityEvent.Type, EntityEvent.Property> tmp;
//------------------------------------------------ --------
The difference I see is that one is abstract and the other is not...
Any ideas?
This question shakes the foundations of many, but the answer is simple: You cannot make a dictionary of events, the closest thing is a dictionary of delegates.
An event adds layers of abstraction and protection over a delegate (or function pointer). This protection by definition only allows adding and removing elements to the invocation list but is not itself a reference to the function pointer (delegate, anonymous function).
This solution doesn't exactly answer the problem, but it has an approach that can help solve it. This suggestion does not pass the letter O of the SOLID principles (Open extension/Closed to changes) because it modifies the interface.
Sources:
Event definition:
[1] https://stackoverflow.com/questions/29155/what-are-the-differences-between-delegates-and-events
Explanatory information.
[2] https://stackoverflow.com/questions/24848332/how-do-i-make-a-dictionary-of-events
Convert System.Action to Delegate.
[3] https://stackoverflow.com/questions/16328589/action-to-delegate-new-action-or-casting-action