错误“存在显式转换(您是否缺少类型转换)"?在创建对象时出现: [英] Error "an explicit conversion exists (are you missing a cast )" comes when creating an object:
本文介绍了错误“存在显式转换(您是否缺少类型转换)"?在创建对象时出现:的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我对学习OOP概念很感兴趣.在尝试使用继承的简单程序时.我已经注意到了这个错误.我不明白为什么会发生此错误?我在下面给出了简单的C#代码:
I am interested in learning OOPs concepts. While trying a simple program using Inheritance. I have noticed this error. I can't understand why this error occur? I have given that simple c# code below:
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();
}
}
任何人都可以告诉我那里到底发生了什么...
Any one please tell me what is actually happening there...
推荐答案
您必须了解每只狗都是动物,但并非所有动物都是狗.
Program
是一个可怕的名字,让我们摆脱它,使其成为Pomeranian
:现在一切都会变得清晰起来.
Program
is a terrible name, let's get rid of that and make it Pomeranian
: now everthing will be clear.
Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian.
但是您可以执行以下操作
but you can do the following
Dog d = new Pomeranian();//You know why this works :)
我希望这会有所帮助.
这篇关于错误“存在显式转换(您是否缺少类型转换)"?在创建对象时出现:的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文