本文介绍了隐藏与重写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 隐藏重写方法的目的是什么?我已经用Google搜索了这个问题,但是没有找到任何有意义的东西。 在下面的代码中,唯一的区别是,当贵宾犬向上倾斜至狗(在其最疯狂的梦想中)它然后说弓哇 bernard 总是说woof (见代码)。基本上,看起来我正在隐藏除了狮子狗以外的所有东西。 我为什么要这样做? ? bob ---------------------------- -------------------------------------------------- ------- class Pets { [STAThread] static void Main(string [] args){ 伯纳德b =新伯纳德(); 贵宾犬p =新贵宾犬(); b.speak(); p.speak(); ((狗)b).speak(); ((狗)p).speak (); 暂停(); } 静态无效暂停(){ Console.Write(" \\\paused"); Console.ReadLine(); } } class Dog { public virtual void speak(){print(" bow wow"); } protected void print(string msg){ Console.WriteLine(" {0}:{1} \ n",this.GetType ().ToString(),msg); } } 班伯纳德:狗{ public override void speak(){print(" woof"); } } class Poodle:Dog { public new void speak(){print(" yip yip yip yip yip yip yip yip yip) yip yip"); } } What is the purpose of hiding intead of overriding a method? I have googledthe question but haven''t found anything that makes any sense of it. In the code below, the only difference is that when the Poodle is upcast tothe Dog (in its wildest dreams) it then says "bow wow" where the bernardalways says "woof" (see code). Basically, it appears that I''m hiding thepoodle''s speak method from everything except the poodle. Why would I want to do this?bob -------------------------------------------------------------------------------------class Pets {[STAThread]static void Main(string[] args) {Bernard b = new Bernard();Poodle p = new Poodle(); b.speak();p.speak(); ((Dog)b).speak();((Dog)p).speak(); pause();} static void pause() {Console.Write("\npaused");Console.ReadLine();}} class Dog {public virtual void speak() { print("bow wow"); } protected void print (string msg) {Console.WriteLine( "{0}: {1}\n", this.GetType().ToString(), msg);}} class Bernard : Dog {public override void speak() { print("woof"); }}class Poodle : Dog {public new void speak() { print("yip yip yip yip yip yip yip yip yipyip"); }}推荐答案 这篇关于隐藏与重写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-16 21:16