【问题标题】:C# Abstract Class : Cannot implicitly convert type type1 to type2C# 抽象类:无法将类型 type1 隐式转换为 type2
【发布时间】:2013-11-18 11:44:24
【问题描述】:

我有一个接口,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();

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

但是我得到了错误:

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

上面的逻辑有问题吗?

谢谢。

【问题讨论】:

  • 你在哪一行得到这个错误? typetype1type2有哪些类型?
  • 嗯,如果您需要像这样的switch 语句,这通常意味着您在设计中做错了。

标签: c# class interface abstract


【解决方案1】:

FoxDeer 应该继承自 Animal 抽象类,您的代码才能正常工作。

即:

public class Deer : Animal
{
     //code
}


public class Fox : Animal
{
     //code
}

【讨论】:

  • 啊,他们正在实现接口,会改变这个并回复你。
  • 然后您可以将它们分配给IAnimal 变量。
  • @CompuChip 但这样他就不需要Animal
  • 拥有抽象类和接口有意义还是只使用抽象类?这是我第一次做这样的事情。感谢您的帮助。
  • 这取决于你需要什么。阅读此msdn.microsoft.com/en-us/library/scsyfw1d(v=vs.71).aspx 了解更多指南
【解决方案2】:

您可以执行以下操作之一:

IAnimal animal; // Notice that it's an IAnimal now
Switch (type)
{
     Case "Fox":
         animal = new Fox();
         break;
     Case "Deer":
         animal = new Deer();
         break;
}

animal.eat();

Animal 类中创建DeerFox 类(在这种情况下,您发布的代码将是相同的)

编辑:

这是根据您发布的代码的类层次结构

        IAnimal
           |
  -------------------
  |        |        |
Animal    Fox     Deer

您可以将派生类型的对象强制转换为更通用的类型(父),因此允许Animal -> IAnimalFox -> IAnimal
但是它不适用于Fox -> Animal 之类的东西,因为Animal 不是 Fox 的父级

【讨论】:

  • 谢谢,不胜感激。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2013-06-30
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
  • 2020-01-14
  • 1970-01-01
相关资源
最近更新 更多