.net接口

特点:

 1.函数前面不能有任何修饰符
 2.只能包含其成员的签名,不能包含任何成员的执行方式(抽象函数没有声明为abstract的函数可以包含执行方式)
 3.只能包含,属性,方法,索引器和事件
 4.不能实例化接口

 5.不能有构造函数,不能有字段(字段隐含了某些内部的执行方式)
 6.不允许有运算符的重载
 7.不允许声明为虚拟的或静态

 8.继承了接口的类必须实现接口中的方法。

View Code
1 interface Interface1
2 {
3 void Say();
4 }
5
6 public class Father : Interface1
7 {
8 //得到一个错误,没有实现接口的方法
9 }
View Code
 1  interface Interface1
2 {
3 void Say(string name);//定义一个说的接口
4 }
5
6 //父亲类继承接口,实现说的方法
7 public class Father : Interface1
8 {
9 public void Say(string name)
10 {
11 Console.WriteLine("我是{0}",name);
12 }
13
14 }
15 //儿子类继承接口实现说的方法
16 class Son :Interface1
17 {
18 public void Say(string name)
19 {
20 Console.WriteLine("我是{0}",name);
21 }
22 }
23
24 static void Main(string[] args)
25 {
26 Interface1 interf = new Father();
27 interf.Say("父亲");
28 Interface1 inters = new Son();
29 inters.Say("儿子");
30 Console.ReadLine();
31 }

接口可以指向任何实现它的类的实例。

还可以通过数组来保存接口的引用

View Code
1 static void Main(string[] args)
2 {
3 Interface1[] inter = new Interface1[2];
4 inter[0]= new Father();
5 inter[1] = new Son();
6 Console.ReadLine();
7 }

派生的接口

接口可以彼此继承,其方式与类的方式相同。

interface Interface1
{
void Say(string name);//定义一个说的接口
}

interface Interface2:Interface1
{
void sing();//定义一个唱的接口
}
View Code
 1  //父亲类继承接口Interface1,Interface2,必须实现Interface1,Interface2中的所有成员
2 public class Father : Interface1,Interface2
3 {
4 public void Say(string name)
5 {
6 Console.WriteLine("我是{0}",name);
7 }
8
9 public void sing()
10 {
11 Console.WriteLine("我会唱歌!");
12 }
13
14 }

在方法中传递接口:

View Code
 1 interface Interface2:Interface1
2 {
3 void sing(Interface1 inter);//定义一个唱的接口
4 }
5
6 public void sing(Interface1 inter)
7 {
8 Console.WriteLine("我会唱歌!");
9 inter.Say("");
10 }








 

posted @ 2012-03-14 14:57  猪特曼  阅读(288)  评论(0编辑  收藏  举报