mercredi 4 juillet 2018

C# - How to convert from inherited type to runtime type

I'm having trouble with handling the correct type on runtime.

I want my code to dynamically detect which handler should be called based on the parameter type. I don't want to cast a TEvent to the correct type in the code.

All handlers inherit from my interface:

public interface IAbstractHandler < in T>  
{
   void Handle(T evnt);
}

Example:

public class SpecificEventHandler: IAbstractHandler< SpecificEvent>
{
   public void Handle(SpecificEvent evnt) {
    ....
   }
}

Here's some code:

List<TEvent> eventItems = new List<TEvent>();
....
foreach (var evt in eventItems) {
  ...
  dynamic eventHandler = ResolveEventHandler(evt.GetType().Name);
  if (evt is MySubtypeEvent subEvent) {
    eventHandler.Handle(subEvent); // <-- this works, but I don't want this.
  }
  eventHandler.Handle(evt); // <-- And this fails, because 'evt' is seemingly 
  // a TEvent even though it's of the correct subclass.
}





Aucun commentaire:

Enregistrer un commentaire