我有兴趣学习 OOP 概念。在尝试使用继承的简单程序时。我注意到这个错误。我不明白为什么会出现这个错误?我给出了下面简单的 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
: 现在一切都会清楚了。
Pomeranian P = new Dog();//This is not valid because not all dogs are Pomeranian.
但你可以执行以下操作
Dog d = new Pomeranian();//You know why this works :)
我希望这有帮助。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)