c# – 新手继承问题
发布时间:2020-12-15 06:50:34 所属栏目:百科 来源:网络整理
导读:我不明白为什么我的输出不是我认为应该的.我认为应该是狗吠线断线猫咪.但没有什么. 码: namespace ConsoleApplication2{ class Program { static void Main(string[] args) { Pets pet1 = new Dog(); Pets pet2 = new Cat(); pet1.Say(); pet2.Say(); Conso
我不明白为什么我的输出不是我认为应该的.我认为应该是狗吠线断线猫咪.但没有什么.
码: namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Pets pet1 = new Dog(); Pets pet2 = new Cat(); pet1.Say(); pet2.Say(); Console.ReadKey(); } } class Pets { public void Say() { } } class Dog : Pets { new public void Say() { Console.WriteLine("Dog barks."); } } class Cat : Pets { new public void Say() { Console.WriteLine("Cat meows."); } } } 我试图通过c# programming guide on MSDN,但是我觉得很难理解那里的一些例子.如果有人可以链接到一个很好的“假人遗产”网站,那将是非常感激的. 解决方法
将您的基类中的Say功能虚拟化,然后在派生类中覆盖此函数:
namespace ConsoleApplication2 { class Program { static void Main(string[] args) { Pets pet1 = new Dog(); Pets pet2 = new Cat(); pet1.Say(); pet2.Say(); Console.ReadKey(); } } class Pets { public virtual void Say() { Console.WriteLine("Pet makes generic noise"); } } class Dog : Pets { public override void Say() { Console.WriteLine("Dog barks."); } } class Cat : Pets { public override void Say() { Console.WriteLine("Cat meows."); } } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |