接口的目的 [英] Purpose of Interface

查看:93
本文介绍了接口的目的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Interface的用途是什么?我们在哪里使用Interface?

解决方案

我倾向于认为接口是Object和'之间的契约' 外部世界。



如果一个Object实现了一个接口,那么它将提供接口定义的那些属性和方法。



单个对象可以实现多个接口,这可能很有用。



多个对象可以实现单个接口,这也很有用。



所以,如果我有两个接口



IDisplayYourselfOnScreen



IMakeANoise



接口只会告诉外面的世界实现IDisplayYourselfOnScreen的对象将具有方法Show()的实现方式和一个Hide();和隐藏的属性;



实现IMakeANoise的对象将有一个方法MakeSound(int volume)。



如果我的主程序现在处理接口,它可以安全地调用实现接口的任何对象上的方法来发出噪音或显示自己,而不用担心如何实现 - 实际上可以完全改变实现而不需要其余的需要更改的应用程序。



因此,如果您正在编写游戏,并且有两个对象发生碰撞,那么您的逻辑可能类似于



  public   void 碰撞(IDisplayYourselfOnScreen object1)
{
object1.Hide();

if (object1实现IMakeANoise)
{
object1.MakeSound( 10 );
}
}





你的object1可能是玩家,敌人,树,无论如何实现一个接口,你保证它会(在某种程度上)响应接口中定义的方法。


只需通过以下链接。它简单易懂。



什么是界面? [ ^ ]



什么是界面?我们为什么要使用它? [ ^ ]



什么时候使用界面? [ ^ ]



抽象类与界面 [ ^ ]



小例子 - C#中的接口(初学者) [ ^ ]


它只是一个只包含方法签名的模板。

它只包含参数个数,参数类型。


What is the use of Interface and where do we use Interface?

解决方案

I tend to think of an Interface as being a contract between an Object and the ''outside world''.

If an Object implements an Interface then it will provide those properties and methods defined by the interface.

A single object can implement multiple interfaces, which can be useful.

Multiple objects can implement a single interface, which can also be useful.

So, if I have two interfaces

IDisplayYourselfOnScreen
and
IMakeANoise

The Interfaces will just tell the outside world that an object implementing the IDisplayYourselfOnScreen will have an implementatino of the method "Show()" and one of Hide(); and a property of Hidden;

An object implementing IMakeANoise will have a method MakeSound(int volume).

If my main program now deals with the Interface, it can safely call methods on any object implementing the Interfaces to make a noise or show themselves, without worrying about how that is implemented - indeed the implementation can be completely changed without the rest of the application needing to be changed.

So if you were writing a game, and had two objects colliding, your logic might be something like

public void Collision(IDisplayYourselfOnScreen object1)
{
    object1.Hide();

   if (object1 implements IMakeANoise)
    {
        object1.MakeSound(10);
    }
}



Your object1 could be the player, an enemy, a tree, whatever, as it implements an interface you guarantee it will respond (in some way) to the methods defined in the interface.


Just go through below links. Its simple and understanding.

What is Interface?[^]

What is Interface? Why do we use it?[^]

When do we use interface?[^]

Abstract Class versus Interface[^]

Small Example - Interfaces in C# (For Beginners)[^]


It is just a template that contains only the signature of a method.
It only consists of the numbers of parameters, the type of parameter.


这篇关于接口的目的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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