教学文库网 - 权威文档分享云平台
您的当前位置:首页 > 精品文档 > 学前教育 >

面向接口编程详解 - 图文(4)

来源:网络收集 时间:2026-08-20
导读: 4 { 5 private IMobileStorage _usbDrive; 6 7 public IMobileStorage UsbDrive 8 { 9 get 10 { 11 return this._usbDrive; 12 } 13 set 14 { 15 this._usbDrive = value; 16 } 17 } 18 19 public Computer() 20 {

4 {

5 private IMobileStorage _usbDrive; 6

7 public IMobileStorage UsbDrive 8

{

9 get 10

{

11 return this._usbDrive; 12 } 13 set 14

{

15 this._usbDrive = value; 16 } 17 } 18

19 public Computer() 20

{

21 } 22

23 public Computer(IMobileStorage usbDrive) 24

{

25 this.UsbDrive = usbDrive; 26 } 27

28 public void ReadData() 29

{

30 this._usbDrive.Read(); 31 }

32

33 public void WriteData() 34

{

35 this._usbDrive.Write(); 36 } 37 } 38}

其中的UsbDrive就是可替换的移动存储设备,之所以用这个名字,是为了让大家觉得直观,就像我们平常使用电脑上的USB插口插拔设备一样。

OK!下面我们来测试我们的“电脑”和“移动存储设备”是否工作正常。我是用的C#控制台程序,具体代码如下: 1namespace InterfaceExample 2

{

3 class Program 4

{

5 static void Main(string[] args) 6

{

7 Computer computer = new Computer();

8 IMobileStorage mp3Player = new MP3Player(); 9 IMobileStorage flashDisk = new FlashDisk();

10 IMobileStorage mobileHardDisk = new MobileHardDisk(); 11

12 Console.WriteLine(\nd copy some music to it:\);

13 computer.UsbDrive = mp3Player; 14 computer.WriteData(); 15 Console.WriteLine();

16

17 Console.WriteLine(\y computer from a mobile hard disk:\);

18 computer.UsbDrive = mobileHardDisk; 19 computer.ReadData(); 20 Console.WriteLine(); 21

22 Console.WriteLine(\h disk and copy another file to it:\); 23 computer.UsbDrive = flashDisk; 24 computer.ReadData(); 25 computer.WriteData(); 26 Console.ReadLine(); 27 } 28 } 29}

现在编译、运行程序,如果没有问题,将看到如下运行结果:

好的,看来我们的系统工作良好。

后来??

刚过了一个星期,就有人送来了新的移动存储设备NewMobileStorage,让我测试能不能用,我微微一笑,心想这不是小菜一碟,让我们看看面向接口编程的威力吧!将测试程序修改成如下:

1namespace InterfaceExample 2

{

3 class Program 4

{

5 static void Main(string[] args)

6 {

7 Computer computer = new Computer();

8 IMobileStorage newMobileStorage = new NewMobileStorage(); 9

10 Console.WriteLine(\); 11 computer.UsbDrive = newMobileStorage; 12 computer.ReadData(); 13 computer.WriteData(); 14 Console.ReadLine(); 15 } 16 } 17}

编译、运行、看结果:

面向接口编程详解 - 图文(4).doc 将本文的Word文档下载到电脑,方便复制、编辑、收藏和打印
本文链接:https://www.jiaowen.net/wendang/595443.html(转载请注明文章来源)
Copyright © 2020-2025 教文网 版权所有
声明 :本网站尊重并保护知识产权,根据《信息网络传播权保护条例》,如果我们转载的作品侵犯了您的权利,请在一个月内通知我们,我们会及时删除。
客服QQ:78024566 邮箱:78024566@qq.com
苏ICP备19068818号-2
Top
× 游客快捷下载通道(下载后可以自由复制和排版)
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
VIP包月下载
特价:29 元/月 原价:99元
低至 0.3 元/份 每月下载150
全站内容免费自由复制
注:下载文档有可能出现无法下载或内容有问题,请联系客服协助您处理。
× 常见问题(客服时间:周一到周五 9:30-18:00)