I have the following interface
public interface IHandler<T>
{
void Handle(T myObject);
}
I’d like to have a HandlersManager class with holds a mapping between object types to their corresponding handler, but I’m not sure how I’m supposed to define the object that hold this mapping.
For example, what I’d like to have is this:
typeof(string) --> instance of IHandler<string>
typeof(MyClass) --> instance of IHandler<MyClass>
The best thing I got so far was to define Dictionary<Type, object> for the mapping, but in this case I would have to cast the value to IHandler<T> every time I get it.
Is there a better solution or something that I have completely missed?
That’s as good as it can get with only a generic
IHandler<T>interface.In order to explore more options, we could define a non-generic version of the interface:
Then you could also define a generic abstract base class that implements both
IHandler<T>andIHandler:At this point you can have an
IDictionary<Type, IHandler>and you can directly callIHandler.Handleon the values you pull out of it:On the other hand we now have an additional interface and an abstract base class just to hide a cast from “user” code, which doesn’t sound very impressive.