我一直在尝试使用泛型,并遇到了一些奇怪的问题。希望你们能给出解释!为了让事情更简单,我把“问题”放到了一个例子中:
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();
}
}
}
所以,我的实验室里有两种动物:一只狗和一只鸟。当我“踢”这些动物时,它们会发出声音。打印机会打印出声音和动物的种类。运行程序后会打印以下内容:
Kick bird: Lab.Animal says 'Tweet!'
Kick dog: Lab.Animal says 'Bark, bark! I'll bite you!'
Print kick dog: Lab.Dog says 'Bark, bark! I'll bite you!'
为什么第一次踢狗会告诉我它是类型为
Lab.Animal
的狗?而且...我怎么才能让它返回Lab.Dog
?