Pet 类型的列表,Pet 有 child classes Dog,Cat 等。我如何分辨它是哪个 child class?
List of type Pet, Pet has child classes Dog, Cat, etc. How do I tell which child class it is?
所以我有一个 "petstore" 控制台程序,它存储一个 Pet 类型的列表,Pet 可以有 child 类 类型的 Dog、Cat、Rabbit 等。所以如果我有一种打印出动物信息的方法,我怎么说它们是哪种动物?
下面是打印动物信息的方法
public void ShowPets()
{
Console.WriteLine("We have these animals: ");
foreach (Pet p in pets)
{
Console.WriteLine(p.Breed + " who is a " + p.Age + " year old " + p.GetType());
}
Console.WriteLine();
}
这是调用该方法时的输出。
terrier who is a 12 year old PetStore.Dog
persian who is a 2 year old PetStore.Cat
所以我想说只有 12 岁的狗或猫或骆驼
而不是 p.GetType()
,试试 p.GetType().Name
。
所以我有一个 "petstore" 控制台程序,它存储一个 Pet 类型的列表,Pet 可以有 child 类 类型的 Dog、Cat、Rabbit 等。所以如果我有一种打印出动物信息的方法,我怎么说它们是哪种动物?
下面是打印动物信息的方法
public void ShowPets()
{
Console.WriteLine("We have these animals: ");
foreach (Pet p in pets)
{
Console.WriteLine(p.Breed + " who is a " + p.Age + " year old " + p.GetType());
}
Console.WriteLine();
}
这是调用该方法时的输出。
terrier who is a 12 year old PetStore.Dog
persian who is a 2 year old PetStore.Cat
所以我想说只有 12 岁的狗或猫或骆驼
而不是 p.GetType()
,试试 p.GetType().Name
。