Let me explain to you in the following example which problem I am solving:
class Animal {} class Cat: Animal {} class Dog : Animal { } interface IAnimalHandler<in T> where T: Animal { void Handle(T animal); } class AnimalHandler : IAnimalHandler<Cat>, IAnimalHandler<Dog> { public void Handle(Cat animal) { Console.Write("it a cat !"); } public void Handle(Dog animal) { Console.Write("it a dog !"); } }
So now I want to go through all the animals and run the appropriate handler as follows:
var ah = new AnimalHandler(); var animals = new List<Animal> { new Cat(), new Dog() }; animals.ForEach(a => ah.Handle(a));
However, this code will not work (the Hanler <> method cannot be resolved) just because the .NET compiler needs to know what type is used here before compiling, so what might be the best solution for this problem? In other words, I need to ask the .NET compiler to take an appropriate type T handler for each instance of type T at runtime . I do not want to use several if
that check the type of the instance.
UPDATE: Sorry for not having it, it seemed obvious to me, but now I understand that it's not so obvious: the AnimalHandler class contains logic that should not be part of the Cat and Dog domain objects. Think of them as pure objects of a regular domain, I do not want them to know about any handlers.
source share