Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>As <a href="https://stackoverflow.com/questions/19283349/c-sharp-generics-wildcards/19302047#comment28574943_19284078">Brian</a> pointed out in comments above, maybe <code>dynamic</code> is the way to go here.</p> <p>Check out the following code. You get the benefits of generics to tie down the API nicely and under the hoods you use <code>dynamic</code> to make things <em>work</em>.</p> <pre><code>public interface IAnimal { } public class Dog : IAnimal { } public class Cat : IAnimal { } public class BigBadWolf : IAnimal { } //I changed `IAnimalGroomer` to an abstract class so you don't have to implement the `AnimalType` property all the time. public abstract class AnimalGroomer&lt;T&gt; where T:IAnimal { public Type AnimalType { get { return typeof(T); } } public abstract void Groom(T animal); } public class CatGroomer : AnimalGroomer&lt;Cat&gt; { public override void Groom(Cat animal) { Console.WriteLine("{0} groomed by {1}", animal.GetType(), this.GetType()); } } public class DogGroomer : AnimalGroomer&lt;Dog&gt; { public override void Groom(Dog animal) { Console.WriteLine("{0} groomed by {1}", animal.GetType(), this.GetType()); } } public class AnimalClinic { private Dictionary&lt;Type, dynamic&gt; groomers = new Dictionary&lt;Type, dynamic&gt;(); public void EmployGroomer&lt;T&gt;(AnimalGroomer&lt;T&gt; groomer) where T:IAnimal { groomers.Add(groomer.AnimalType, groomer); } public void Groom(IAnimal animal) { dynamic groomer; groomers.TryGetValue(animal.GetType(), out groomer); if (groomer != null) groomer.Groom((dynamic)animal); else Console.WriteLine("Sorry, no groomer available for your {0}", animal.GetType()); } } </code></pre> <p>And now you can do:</p> <pre><code>var animalClinic = new AnimalClinic(); animalClinic.EmployGroomer(new DogGroomer()); animalClinic.EmployGroomer(new CatGroomer()); animalClinic.Groom(new Dog()); animalClinic.Groom(new Cat()); animalClinic.Groom(new BigBadWolf()); </code></pre> <p>I'm not sure if this is somewhat what you were looking for. Hope it helps!</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload