我想知道如何在不知道类型的情况下传递对象的实例。我想知道这一点,因为如果我有100种动物类型,那么我不想有100个if语句或转换。我提供了一个片段,这是我想要基本实现的一个例子。现在,在我发表评论的地方显然不起作用。在不知道类型的情况下传递类的实例
using System.IO;
using System;
using System.Collections.Generic;
class Program
{
Dictionary<string, dynamic> myAnimals = new Dictionary<string, dynamic>();
Program(){
myAnimals.Add("Maggie", new Dog("Maggie"));
myAnimals["Maggie"].bark();
myAnimals.Add("Whiskers", new Cat("Whiskers"));
myAnimals["Whiskers"].meow();
animalClinic clinic = new animalClinic();
clinic.cureAnimal(myAnimals["Whiskers"]);
}
static void Main()
{
new Program();
}
}
class Dog{
string name;
public Dog(string n){
name = n;
}
public void bark(){
Console.WriteLine("\"Woof Woof\" - " + name);
}
}
class Cat{
string name;
public Cat(string n){
name = n;
}
public void meow(){
Console.WriteLine("\"Meow Meow\" - " + name);
}
}
class animalClinic(){
public void cureAnimal(object animal){ //This is where I need some help.
if(animal.name == "Maggie"){ //I know I can use 'animal.GetType() == ...' That isn't the point.
Console.WriteLine("We heal fine dogs!"); //The point is to access various methods within the object.
}else{//I know it kind of beats the point of Type-Safety, but this is only an example and another way to do this is perfectly fine with me.
Console.WriteLine("Eww a cat!")
}
}
}
如果有人知道替代解决方案,请继续分享!
谢谢。
编辑:我想你还需要引用动物而不是仅仅传递它。
你为什么要创建在animalClinic每个动物类型明确分开的方法来提供?为什么不只是治愈动物(内动物)和动物。描述或任何适当的财产?看起来你在这里颠覆了多态的全部观点。 – Jeb 2014-12-27 18:32:04
我试图展示两种技术......有时候你想要像这样的功能来生活在代码库的不同位置。但是这不起作用,因为Dictionary不支持类型差异。编辑即将到来。 – 2014-12-27 18:36:12