【C#概念学习】接口

接口

一、特点:
1、包括四个成员:方法、属性、索引器(有参属性)和事件。
2、方法的实现是在实现接口的类中完成的。
3、接口默认为public,不能显示指定方法的public类型。
4、不能实现实例化。

二、实现方式:
1、显式
2、隐式

例如:

 1 //定义接口
 2 interface IGraphic
 3 {
 4     float getArea();
 5 }
 6 
 7 
 8 //隐式实现接口
 9 public class Rectangle : IGraphic
10 {
11     private float _width = 10;
12     private float _height = 10;
13 
14     #region IGraphic 成员
15     public float getArea()
16     {
17         return _width * _height;
18     }
19     #endregion
20 }
21 
22 //隐式实现接口
23 public class Rectangle : IGraphic
24 {
25     private float _width = 10;
26     private float _height = 10;
27 
28     #region IGraphic 成员
29     public float IGraphic.getArea()
30     {
31         return _width * _height;
32     }
33     #endregion
34 }
35 
36 //实现方式
37 static void Main(string[] args)
38 {
39     //调用方式1
40     IGraphic graphic = new Rectangle();
41     float area = graphic.getArea();
42     Console.Write(area.ToString());
43     Console.Read();
44     
45     //调用方式2
46     Rectangle rectangle = new Rectangle();
47     area = rectangle.getArea();
48     Console.Write(area.ToString());
49     Console.Read();
50 }

 

其中:
1、隐式实现方式:【调用方式1】 和 【调用方式2】 都可以用。
2、显示实现方式:只能使用 【调用方式1】。

总结:
从接口的定义方面来说,接口其实就是类和类之间的一种协定,一种约束。从调用者角度来说,
如果他知道了某个类是继承于IGraphic接口,那么他就可放心调用getArea方法。再就是如果接
口显式实现,就可以限制调用者只能通过接口调用了。

 

 

 

 

 

posted @ 2012-09-28 09:35  tech.JL  阅读(167)  评论(0编辑  收藏  举报