在Ruby中,什么是等价于C#的接口? [英] In Ruby, what is the equivalent to an interface in C#?

查看:162
本文介绍了在Ruby中,什么是等价于C#的接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在努力学习Ruby和我试图了解更多关于封装和合同条款它所提供。​​



在C#中的合同会使用接口来定义。它实现了接口的类必须提供每个方法和定义的属性(也许其他的东西)的实施履行合同中的条款。个别类实现一个接口可以做任何它需要的合同规定,只要它接受相同类型的参数并返回相同类型的结果的方法的范围之内。



有没有办法强制执行这种事情在Ruby中?



感谢




我的意思在C#一个简单的例子:

 接口IConsole 
{
INT MaxControllers {获得;}
无效琐事(iGame的游戏);
}

类的Xbox360:IConsole
{
公众诠释MaxControllers
{
得到{4; }
}

公共无效琐事(的iGame游戏)
{
InsertDisc(游戏);
NavigateToMenuItem();
单击();
}
}

类NES:IConsole
{
公众诠释MaxControllers
{
得到{2; }
}

公共无效琐事(的iGame游戏)
{
InsertCartridge(游戏);
TurnOn();
}
}



解决方案

有在Ruby中没有接口,因为Ruby是动态类型语言。接口基本上都是用来制造不同类别不破坏类型安全互换。你的代码可以与每一个控制台工作,只要它像它在C#装置完成IConsole控制台。 鸭打字是一个关键词,你可以用它来赶上处理这类问题的动态语言的方式。



此外,您可以和应该写单元测试验证您的代码的行为。每个对象都有你可以在你的断言使用的respond_to?方法。


I'm currently trying to learn Ruby and I'm trying to understand more about what it offers in terms of encapsulation and contracts.

In C# a contract can be defined using an interface. A class which implements the interface must fulfil the terms within the contract by providing an implementation for each method and property (and maybe other things) defined. The individual class that implements an interface can do whatever it needs within the scope of the methods defined by the contract, so long as it accepts the same types of arguments and returns the same type of result.

Is there a way to enforce this kind of thing in Ruby?

Thanks

A simple example of what I mean in C#:

interface IConsole
{
    int MaxControllers {get;}
    void PlayGame(IGame game);
}

class Xbox360 : IConsole
{
   public int MaxControllers
   {
      get { return 4; }
   }

   public void PlayGame(IGame game)
   {
       InsertDisc(game);
       NavigateToMenuItem();
       Click();
   }
}

class NES : IConsole
{
    public int MaxControllers
    {
        get { return 2; }
    }

   public void PlayGame(IGame game)
   {
       InsertCartridge(game);
       TurnOn();
   }
}

解决方案

There are no interfaces in ruby since ruby is a dynamically typed language. Interfaces are basically used to make different classes interchangeable without breaking type safety. Your code can work with every Console as long it behaves like a console which in C# means implements IConsole. "duck typing" is a keyword you can use to catch up with the dynamic languages way of dealing with this kind of problem.

Further you can and should write unit tests to verify the behavior of your code. Every object has a respond_to? method you can use in your assert.

这篇关于在Ruby中,什么是等价于C#的接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆