为什么我似乎无法掌握界面? [英] Why can't I seem to grasp interfaces?

查看:27
本文介绍了为什么我似乎无法掌握界面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以为我揭开界面的神秘面纱,或者给我一些好的例子吗?我不断地看到界面弹出,但我从来没有真正接触过界面的良好解释或何时使用它们.

Could someone please demystify interfaces for me or point me to some good examples? I keep seeing interfaces popup here and there, but I haven't ever really been exposed to good explanations of interfaces or when to use them.

我是在接口与抽象类的上下文中谈论接口.

I am talking about interfaces in a context of interfaces vs. abstract classes.

推荐答案

接口允许您根据描述"而不是类型进行编程,这允许您更松散地关联软件元素.

Interfaces allow you to program against a "description" instead of a type, which allows you to more-loosely associate elements of your software.

这样想:您想与旁边立方体中的某个人共享数据,因此您拔出闪存棒并复制/粘贴.你走到隔壁,那家伙说那是 USB 吗?"你说是 - 一切就绪.闪存盘的大小和制造商无关 - 重要的是它是 USB.

Think of it this way: You want to share data with someone in the cube next to you, so you pull out your flash stick and copy/paste. You walk next door and the guy says "is that USB?" and you say yes - all set. It doesn't matter the size of the flash stick, nor the maker - all that matters is that it's USB.

以同样的方式,接口允许您将开发通用化.使用另一个类比 - 假设您想创建一个虚拟绘制汽车的应用程序.你可能有这样的签名:

In the same way, interfaces allow you to generisize your development. Using another analogy - imagine you wanted to create an application that virtually painted cars. You might have a signature like this:

public void Paint(Car car, System.Drawing.Color color)...

这会一直有效,直到您的客户说现在我想给卡车上漆",所以您可以这样做:

This would work until your client said "now I want to paint trucks" so you could do this:

public void Paint (Vehicle vehicle, System.Drawing.Color color)...

这会拓宽您的应用程序...直到您的客户说现在我想粉刷房屋!"你从一开始就可以做的是创建一个界面:

this would broaden your app... until your client said "now I want to paint houses!" What you could have done from the very beginning is created an interface:

public interface IPaintable{
   void Paint(System.Drawing.Color color);
}

...并将其传递给您的例程:

...and passed that to your routine:

public void Paint(IPaintable item, System.Drawing.Color color){
   item.Paint(color);
}

希望这是有道理的 - 这是一个非常简单的解释,但希望能抓住它的核心.

Hopefully this makes sense - it's a pretty simplistic explanation but hopefully gets to the heart of it.

这篇关于为什么我似乎无法掌握界面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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