Delegate Arguments - Base- / Derived Classes conflict

时间:2017-04-06 16:55:47

标签: c#

I'm a bit of a noob when it comes to C#, which is why i come to you all in hopes for some clarification. I have a EventDispatcher Class that defines a delegate:

delegate void EventHandler(BaseEvent evt);

and a few methods to use it:

void AddEventListener(string event_name, EventHandler handler)
void RemoveEventListener(string event_name, EventHandler handler = null)
void DispatchEvent(BaseEvent evt)

I also have derived Event Classes for Example DerivedEvent that inherits from BaseEvent and adds their own properties/fields on top.

As expected i would use it like so:

AddEventListener("my_event", MyEventHandler);

and my Handler Method would look something like this:

void MyEventHandler(BaseEvent evt)

Finally, the actual problem. Why can't i define a Handler that uses the derived event class as argument, like so:

void MyEventHandler(DerivedEvent evt)

I've tried even via Interfaces but that made no difference. I am currently casting within the method-body to the actual Event Class:

...
DerivedEvent actualEvent = (DerivedEvent)evt;
...

Is that really the only way? Hopefully somebody can enlighten me :)

1 个答案:

答案 0 :(得分:0)

When the delegate is called the caller is allowed to pass in any BaseEvent. It isn't necessarily a DerivedEvent. Since the caller might be passing in an object that isn't a DerivedEvent, your handler can't assume that the value passed in is a DerivedEvent.

What you can do is add a handler that can accept not only any BaseEvent, but also other things. For example, you could add a handler that accepts object as a parameter, because any BaseEvent that is passed in when the handler is invoke will be an object.