您如何在Ruby中进行多态?

编程入门 行业动态 更新时间:2024-10-06 22:22:07
本文介绍了您如何在Ruby中进行多态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

在C#中,我可以这样做:

In C#, I can do this:

class Program { static void Main(string[] args) { List<Animal> animals = new List<Animal>(); animals.Add(new Dog()); animals.Add(new Cat()); foreach (Animal a in animals) { Console.WriteLine(a.MakeNoise()); a.Sleep(); } } } public class Animal { public virtual string MakeNoise() { return String.Empty; } public void Sleep() { Console.Writeline(this.GetType().ToString() + " is sleeping."); } } public class Dog : Animal { public override string MakeNoise() { return "Woof!"; } } public class Cat : Animal { public override string MakeNoise() { return "Meow!"; } }

很明显,输出是(略有释义):

Obviously, the output is (Slightly paraphrased):

  • 编织
  • 狗在睡觉
  • 猫在睡觉

由于C#经常因其冗长的类型语法而被嘲笑,您如何使用诸如Ruby之类的鸭式语言处理多态/虚拟方法?

Since C# is often mocked for its verbose type syntax, how do you handle polymorphism/virtual methods in a duck typed language such as Ruby?

推荐答案

为您更新的问题添加了更多代码

edit: added more code for your updated question

免责声明:我已经有大约一年没有使用Ruby了,并且没有在该机器上安装Ruby,因此语法可能完全错误.但是这些概念是正确的.

disclaimer: I haven't used Ruby in a year or so, and don't have it installed on this machine, so the syntax might be entirely wrong. But the concepts are correct.

完全相同的方法,包括类和重写的方法:

The exact same way, with classes and overridden methods:

class Animal def MakeNoise return "" end def Sleep print self.class.name + " is sleeping.\n" end end class Dog < Animal def MakeNoise return "Woof!" end end class Cat < Animal def MakeNoise return "Meow!" end end animals = [Dog.new, Cat.new] animals.each {|a| print a.MakeNoise + "\n" a.Sleep }

更多推荐

您如何在Ruby中进行多态?

本文发布于:2023-11-23 06:57:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1620526.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多态   如何在   Ruby

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!