C#:study(8)--接口

@接口(interface)

  • 接口只提供定义,除了方法,接口还定义了属性索引事件。接口不能包括数据成员,也不能定义构造函数、析构函数和运算符方法。任何方法都不能声明为static。
  • 实现接口的类必须提供接口继承链中定义的所有成员的实现,接口中的方法默认为public,不用显式指定访问属性。
  • 接口可以多继承
  • 接口中的所有成员都是公有的

 

 1 public interface Series
 2 {
 3 int getNext();
 4 void reset();
 5 void setStart(int x);
 6 }
 7 
 8 public ByTwos : Series
 9 {
10 int start;
11 int val;
12 int prev;
13 public ByTwos()
14 {
15 start = 0;val = 0;prev = -2;
16 }
17 public int getNext()
18 {
19 prev = val;val += 2;return val;
20 }
21 public void reset()
22 {
23 start = 0;val = 0;prev = -2;
24 }
25 public void setStart(int x)
26 {
27 start = x;val = x;prev = x - 2;
28 }
29 int getPrevious()//新添的方法
30 {
31 return prev;
32 }
33 }

@使用接口引用
        当通过接口引用调用对象的方法时,该方法就是执行对象实现的方法版本。类似于基类引用访问派生类对象的情况。
 1 class SeriesDemo2
 2 {
 3 public static void Main()
 4 {
 5 ByTwos twoOb = new ByTwos();
 6 ByThrees threeOb = new ByThrees();
 7 Series ob;
 8 
 9 for(int i = 0;i < 5;i++)
10 {
11 ob = twoOb;//1
12 Console.WriteLine("Next ByTwos values is " + ob.getNext());
13 ob = threeOb;//2
14 Console.WriteLine("Next threeOb values is " + ob.getNext());
15 }
16 }
17 }

@接口属性和接口索引
 1 public interface Series
 2 {
 3 //接口属性
 4 int next
 5 {
 6 get;
 7 set;
 8 }
 9 //接口索引
10 int this[int index]
11 {
12 get;
13 }
14 }

@显式实现接口的方法
        作用一、当使用全称作用域实现一个方法时,就相当于提供了不是处于类外代码的一个私有实现。
//显式实现一个接口成员
using System;
interface IEven
{
bool isOdd(int x);
bool isEven(int x);
}


class Myclass : IEven
{
bool IEven.isOdd(int x)//显式实现
{
if((x%2)!=0return true;
else return false;
}

public bool isEven(int x)
{
IEven o 
= this;//当前对象的引用
return !o.isOdd(x);
}

}


class Demo
{
public static voic Main()
{
MyClass ob 
= new MyClass();
bool result;
result 
= ob.isEven(4);
if(result)
Console.WriteLine(
"4 is even.");
else
Console.WriteLine(
"3 is odd");

//result = ob.isOdd;//error,不是暴露的!!!
}

}

        既然显式实现了方法isOdd(),该方法就对MyClass以外的代码无效。这样该实现就是私有的。在MyClass的内部,只能通过一个接口引用来访问方法isOdd()。这就是isEven()的实现中通过o调用方法isOdd()的原因。

        作用二、消除岐义
 1 //使用显式实现消除岐义
 2 using System;
 3 interface IMyIF_A
 4 {
 5 int meth(int x);
 6 }
 7 interface IMyIF_B
 8 {
 9 int meth(int x);
10 }
11 
12 //MyClass实现了两个接口
13 class MyClass : IMyIF_A,IMyIF_B
14 {
15 IMyIF_A a_ob;
16 IMyIF_B b-ob;
17 int IMyIF_A.meth(int x)
18 {
19 return x + x;
20 }
21 int IMyIF_B.meth(int x)
22 {
23 return x * x;
24 }
25 
26 public int methA(int x)
27 {
28 a_ob = this;
29 return a_ob.meth(x);
30 }
31 public int methB(int x)
32 {
33 b_ob = this;
34 return b_ob.meth(x);
35 }
36 }

posted @ 2005-08-20 09:03  zhh007's Bolg  阅读(186)  评论(0编辑  收藏  举报