In C #, how can I omit the previous upstream object without knowing its type?

I have an interface method

  public void Execute(ICommand command);

      

which needs to pass known subtypes ICommand

into a suitable method implementation Handle(SpecificCommand command)

and do some general handling of unknown types. I'm looking for a versatile (i.e., not requiring a giant switch) way of doing this, something similar to

  Handle(command as command.GetType()); // this obviously does not compile

      

I know I can register handlers in some way, eg. store them as delegates in the dictionary, but this still requires duplication of processing logic (once in a specific method signature Handle(...)

, once in a delegation). If I populate a dictionary by checking my class with reflection (looking for methods Handle(XXX command)

) I get a performance hit.

To summarize: how can I omit an object (promoted to call to Execute(ICommand command)

) to call a method that requires a particular type without knowing what type it is at compile time.

+1


source to share


4 answers


The listing is generated at compile time, so you need to know the type at compile time. Overloading is also defined at compile time - so by the time you actually know the specific type, it's too late.

I don't see you really duplicating any logic with delegates. Alternatively, if you are doing it with reflection, you can easily create delegates using Delegate.CreateDelegate - you only get one performance hit and everything will be very fast after that. For more information see my blog post article about Delegate.CreateDelegate .



I think I decided to use a manual dictionary or one built with reflection based on how many methods I had and how often they change. You will probably find KeyedByTypeCollection useful for a dictionary.

+5


source


Well, the "correct" answer is that Handle () should be a method in ICommand, so instead Handle(command)

you would say command.Handle()

.



+9


source


You can't and why do you want?

That's the whole reason why we have polymorphism. If you want to have custom behavior specific to certain types, then the behavior must live in the type itself and be called through a function declared in the base class.

+2


source


I tried to develop a way that would work with Double Dispatch ( http://en.wikipedia.org/wiki/Double_dispatch ), but it seems that you have a situation where the number of classes that implement ICommand and those that implement Execute () can change at runtime (or at least between compilation and runtime, which are essentially the same thing), so the only solution I see is a dictionary like Jon Skeet commandeered.

+1


source







All Articles