考虑以下代码:
class BaseEvent {}
class DummyEvent : BaseEvent {}
void FooBase(BaseEvent e) {}
void FooDummy(DummyEvent e) {}
void main(String[] args) {
Action<BaseEvent> actionBase = FooBase;
Action<DummyEvent> actionDummy = FooDummy;
// Works implicit
Action<DummyEvent> actionDummy2 = actionBase;
// Only explcit
Action<BaseEvent> actionBase2 = (Action<BaseEvent>)actionDummy;
}
我不明白为什么它会像这样工作,考虑它如何与对象引用一起工作,它会不会更有意义呢?
void main(String[] args) {
BaseEvent baseEvent = new BaseEvent();
DummyEvent dummyEvent = new DummyEvent();
// Works implicit
BaseEvent baseEvent2 = dummyEvent;
// Only explicit
DummyEvent dummyEvent2 = (DummyEvent)baseEvent2;
}
我想编写存储Action of Map的代码并传入不同的事件,如下所示:
class EventManager {
Dicionary<int, Action<BaseEvent>> eventHandlers = new Dicionary<int, Action<BaseEvent>>();
public void AddHandler(int eventType, Action<BaseEvent> eventHandler) {
eventHandlers.Add(eventType, eventHandler);
}
public void TriggerEvent(BaseEvent e) {
eventHandlers[e.EventType](e);
}
}
void HandleDummyEvent(DummyEvent e)
{
// Some code
}
void main(String[] args) {
EventManager eventManager = new EventManager();
eventManager.AddHandler(DummyEvent.EventType, HandleDummyEvent);
eventManager.TriggerEvent(new DummyEvent());
}