什么是“接口”?

by Qian 10/14/2007 10:29:00 PM

学习了C#这么久,有一个问题一直困扰着我,那就是什么是“接口”。感谢SmileBest的帮助,给了我一个非常浅显但是很贴切的例子。

简单的说,接口解释定义了一个合同。比如说我有个接口定义,需要有个方法叫PrintPrice()打印价格。那么实现该接口的所有类都必须有该方法,就是说我不管你具体是什么类,只要实现了这个接口,就肯定有这个方法。

例子是:比如有个超市,里面有很多商品。我们设计每个商品用一个类实现。现在我有个主程序需要获得每个商品的价格,因此每个商品的类需要一个提供自己商品价格的函数。为了确保这个主程序去调用每个商品类的时候都能获得这个价格函数。我们定义了一个接口。这个接口定义了一个方法叫GetPrice。我写所有商品类的时候都实现这个接口,就是说每个商品类都会有这个方法,那么主程序只需要判断商品类是不是实现了这个接口,如果实现了,就肯定能获得这个商品的价格。

其实就是说接口就是定义了一个合同,实现这个接口的类都保证自己符合这个合同要求。

Currently rated 4.5 by 2 people

  • Currently 4.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: ,

ASPX + C#

Copyright © 2009 Qian (Denis) Yu.
ICP Registration (Shanghai): No.05011355
Powered by BlogEngine.NET 1.2.0.0, Theme by Mads Kristensen

About the author

Name of author Qian (Denis) Yu
Please visit my website

E-mail me Send mail

Calendar

<<  January 2009  >>
MoTuWeThFrSaSu
2930311234
567891011
12131415161718
19202122232425
2627282930311
2345678

View posts in large calendar

Recent posts

Recent comments

    Disclaimer

    The content on this site represents my own personal opinions and thoughts at the time of posting, and does not reflect those of my employer's in any way.