为什么我似乎无法掌握接口? [英] Why can't I seem to grasp interfaces?
问题描述
有人可以为我揭开界面的神秘面纱,还是给我一些好的例子?我一直在这里和那里看到界面弹出,但我还没有真正接触到界面的好解释或何时使用它们。
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屋!