在C#中的接口 [英] Interfaces in C#

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

问题描述

我要寻找的接口在C#中一个非常简单的解释。我一直在问谷歌,但我得到的答案是非常技术性的和在某种程度上程序员可以理解的措辞。它几乎听起来像一个可以执行一个功能被调用的方法,它允许程序员使用较少的击键。

I am looking for a really simple explanation of interfaces in C#. I have been asking google but the answers I get are very technical and worded in a way a programmer might understand. It almost sounds like a method that can be called in order to perform a function, It allows the programmer to use less key strokes.

从我正在读下面的接口是创建方法做同样的事情,但不同的技术容器的方法。

From what I am reading below interfaces are a way to create a container of method that do the same thing but with different technologies.

我想知道它们是什么?他们做什么?我可能会使用他们?

I would like to know what they are? What they do? What I might use them for?

推荐答案

假设你有一个比萨饼店(我偷了由著名设计这个例子模式一书)。你知道,所有的比萨饼需要订购,准备,烘烤和盒装。嗯,你可以定义这个共同的行为变成一个接口:

Imagine that you have a pizza store (I'm stealing this example from a famous Design Patterns book). You know that all pizzas need to be ordered, prepared, baked and boxed. Well, you can define this common behavior into an interface:

public interface IPizza
{
   void Order();
   void Prepare();
   void Bake();
   void Box();
}

和你有不同的比萨饼实现该接口。当你实现一个接口,你迫使这个类有相同的方法和参数的接口,例如:

And have your different kinds of pizzas implement that interface. When you implement an interface, you're forcing that class to have the same methods and parameters as the interface, for example:

public class PepperoniPizza : IPizza
{
   public void Order()
   {
       //Order Pepperoni pizza
   }

   public void Prepare()
   {
       //Prepare Pepperoni pizza
   }

   public void Bake()
   {
       //Bake Pepperoni pizza
   }

   public void Box()
   {
       //Box Pepperoni pizza
   }
}

您会非常有夏威夷,奶酪或任何其他比萨饼一样。

You would pretty much have the same with Hawaiian, Cheese or any other Pizza.

在现实生活中有几种用途接口。您可以创建合同来扩展应用程序,或者确保它适用于不同的情况。

In real life there are several uses for Interfaces. You can create contracts to extend an application, or ensure that it works on different situations.

希望这有助于

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

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