创建对象时出现错误“存在显式转换(您是否错过了转换)”:

我有兴趣学习OOP概念。 在尝试使用inheritance的简单程序时。 我注意到了这个错误。 我无法理解为什么会出现这种错误? 我在下面给出了简单的c#代码:

class Animal { public void Body() { Console.WriteLine("Animal"); } } class Dog : Animal { public void Activity() { Console.WriteLine("Dog Activity"); } } class Pomeranian : Dog { static void Main(string[] args) { //Dog D = new Dog(); Dog D = new Pomeranian(); -----> No error occur at this line Pomeranian P = new Dog(); -----> Error occur at this line D.Body(); D.Activity(); Console.ReadLine(); } } 

任何人请告诉我那里发生了什么……

您必须了解每只狗都是动物的概念,但并非所有动物都是狗

Program是一个可怕的名字,让我们摆脱它并使它成为Pomeranian :现在everthing将是明确的。

 Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian. 

但你可以做到以下几点

 Dog d = new Pomeranian();//You know why this works :) 

我希望这有帮助。

您无法从类型child创建父实例。 它违反了inheritance的概念。

博美犬是狗,但狗不一定是博美犬。 这在现实生活中是正确的,当你的面向对象的类正确地相互inheritance时,这是真的。 在现实生活中,您对狗进行DNA测试以validation它是博美犬。 在.NET Framework中,我们有一些函数和运算符可以帮助我们解决这个问题。

假设你肯定知道你的Dog的实例实际上是Pomeranian Dog 。 您可以执行显式转换。

 Dog dog = new Pomeranian(); Pomeranian pomeranian = (Pomeranian)dog; //explicit cast. This works. Would throw an InvalidCastException if the dog isn't a Pomeranian 

您希望确定实例实际上是您要转换的类型,以避免exception。 一种方法是使用GetType()typeof()

 Dog dog = new Pomeranian(); if(dog.GetType() == typeof(Pomeranian)) { Pomeranian p = (Pomeranian)dog; //explicit cast won't throw exception because we verified what we're doing is valid. } 

另一种方法是使用as运算符。

 Dog dog = new Pomeranian(); Pomeranian pomeranian = dog as Pomeranian; //If the dog isn't actually a Pomeranian, the pomeranian would be null. 

使用as运算符基本上相当于……

 Dog dog = new Pomeranian(); Pomeranian pomeranian = null; if(dog.GetType() == typeof(Pomeranian)) { pomeranian = (Pomeranian)dog; } 

显然,当你的所有代码都是同一个块时,很容易通过观察它来分辨基础类型。 但是当你开始使用generics集合和其他类似的东西并且你在类之间传递它们时,有时候你不知道类型是什么,并且在铸造之前检查类型变得很重要。

请参阅MSDN上的转换和类型转换 。

Program子类Dog以来,您无法从Dog那里获得Program

但是对于多态性,一个Program是一个Dog ,但不是相反。