When are generic types defined? Could this affect?

I played with generics and I saw some strange things. Hope you guys have an explanation! To keep things simple, I put the β€œproblem” as an example:

namespace Lab { public class Animal { public Animal(string sound) { this.Sound = sound; } public string Sound { get; private set; } public void Kick() { Printer.Print(this, Sound); } } public class Dog : Animal { public Dog() : base("Bark, bark! I'll bite you!") { } } public class Printer { public static void Print<T>(T obj, string message) { System.Console.WriteLine("{0} says '{1}' \n", typeof(T).FullName.PadRight(10), message); } } public static class Program { static void Main(string[] args) { Animal bird = new Animal("Tweet!"); Dog dog = new Dog(); System.Console.WriteLine("Kick bird:"); bird.Kick(); System.Console.WriteLine("Kick dog:"); dog.Kick(); System.Console.WriteLine("Print kick dog:"); Printer.Print(dog, dog.Sound); System.Console.ReadLine(); } } } 

So, I have two animals in my laboratory: a dog and a bird. When I "kick" these animals, they will make a sound. The printer will print the sound and type of animal. When I run the program, it prints:

Kill the bird: Lab.Animal says: "Tweet!"

Shock dog: Lab.Animal says: "Bark, bark! I will bite you!"

Type a pin-dog: Lab.Dog says: "Bark, bark! I'll bite you!"

Why does the dog’s first blow tell me that it is a Lab.Animal type? And ... how can I return it to Lab.Dog ?

+8
generics methods
source share
2 answers

The first hit of the dog tells you that the compile time type of the type argument was Lab.Animal. In other words, your Animal.Kick method Animal.Kick efficient:

 Printer.Print<Animal>(this, Sound); 

Type arguments are not polymorphically defined - they are determined at compile time. This becomes more complicated when an argument of the type of a single call is actually a parameter of the type of the calling context, but it is basically the same.

To say " Lab.Dog ", you will need to get the actual runtime type of the object, for example. using

 obj.GetType().FullName 
+6
source share

Typically, generators are determined at compile time, but also perform a run-time function. In this case, you are using a generic type of output that uses variables, etc. For type inference.

In the method:

  public void Kick() { Printer.Print(this, Sound); } 

all that is known in this in this context is that it must be Animal , so there is an implicit Anmial, i.e. Printer.Print<Animal>(this, Sound)

Other parameters:

  • use GetType() to find the actual type of the object
  • use dynamic to delay resolution at runtime (note, not ideal using dynamic, but it works)
+3
source share

All Articles