C#抽象类:不能将类型type1隐式转换为type2

mit*_*llt 1 c# interface class abstract

我有一个接口,3个实现接口的类,其中一个类应该是抽象的.

iAnimal // Interface
Animal // Abstract Class (Implements iAnimal)
Fox // Class (Implements iAnimal)
Deer // Class (Implements iAnimal)

Animal animal; // declare an animal
Switch (type)
{
     Case "Fox":
         animal = new Fox();
         break;
     Case "Deer":
         animal = new Deer();
         break;
}

animal.eat();
Run Code Online (Sandbox Code Playgroud)

我只想在动物身上调用eat函数,这是switch语句的结果.

但是我得到错误:

无法将type1类型隐式转换为type2.

上述逻辑有什么问题吗?

谢谢.

gza*_*axx 5

Fox并且Deer应该从Animal抽象类继承,以使您的代码正常工作.

即:

public class Deer : Animal
{
     //code
}


public class Fox : Animal
{
     //code
}
Run Code Online (Sandbox Code Playgroud)

  • 这取决于你需要什么.阅读此http://msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx了解更多指南 (2认同)