C#interface定义及使用浅析

开发 后端
C# interface定义及使用的问题是我们在实际开发中会遇到的,那么有什么具体的解决思路呢?那么本文就向你介绍相关的内容。

C# interface定义及使用的问题:接口定义以大写字母I开头。方法只定义其名称,在C#中,方法默认是公有方法;用public修饰方法是不允许的,否则会出现编译错误;接口可以从别的接口继承,如果是继承多个接口,则父接口列表用逗号间隔。

C# interface可以通过类来实现,当类的基列表同时包含基类和接口时,列表中首先出现的是基类;类必须要实现其抽象方法;

C# interface定义及使用实例:

  1. using System;  
  2. namespace Dage.Interface   
  3. {  
  4.  //打印机接口  
  5.  public interface IPrint  
  6.  {  
  7.   string returnPrintName();  
  8.  }  
  9. }  
  10. //C# interface应用实现  
  11. using System;  
  12. using Dage.Interface;  
  13. namespace Dage.Print  
  14. {  
  15.  //HP牌打印机类  
  16.  public class HP: IPrint  
  17.  {  
  18.   public string returnPrintName()  
  19.   {  
  20.    return "这是HP牌打印机";  
  21.   }  
  22.  }  
  23. }  
  24. //C# interface应用实现  
  25. using System;  
  26. namespace Dage.Print  
  27. {  
  28.  //Eps牌打印机类  
  29.  public class Eps: IPrint  
  30.  {  
  31.   public string returnPrintName()  
  32.   {  
  33.    return "这是Eps牌打印机";  
  34.   }  
  35.  }  
  36. }  
  37. //C# interface应用实现  
  38. using System;  
  39. using Dage.Interface;  
  40. namespace Dage  
  41. {  
  42.  //打印类  
  43.  public class Printer  
  44.  {  
  45.   public Printer()  
  46.   {}  
  47.   public string PrintName(IPrint iPrint)  
  48.   {  
  49.    return iPrint.returnPrintName();  
  50.   }  
  51.  }  
  52. }  
  53. //C# interface应用实现  
  54. --WinFrom中调用代码:  
  55. private void button1_Click(object sender, System.EventArgs e)  
  56. {  
  57.  Printer p= new Printer();  
  58.  switch (this.comboBox1.Text)  
  59.  {  
  60.   case "HP":  
  61.    MessageBox.Show(p.PrintName(new HP()));  
  62.    break;  
  63.   case "Eps":  
  64.    MessageBox.Show(p.PrintName(new Eps()));  
  65.    break;  
  66.   default:  
  67.    MessageBox.Show("没有发现这个品牌!");  
  68.    break;  
  69.  }  

C# interface定义与使用的基本内容和相关的理解就向你介绍到这里,希望对你了解和学习C# interface的定义与使用有所帮助。

【编辑推荐】

  1. C#语法基础浅析
  2. 详解C#break ,continue, return
  3. 浅析C#接口特点及实例应用
  4. C# interface实例浅析
  5. C# interface编程应用浅析
责任编辑:仲衡 来源: 博客园
相关推荐

2009-08-27 13:30:11

C# interfac

2009-08-27 14:12:02

C# interfac

2009-08-31 16:37:20

C#接口定义

2009-08-27 17:11:44

C# Fluent I

2009-07-06 09:23:51

Servlet定义

2009-08-27 17:33:51

Interface接口

2009-08-27 15:17:18

C# interfacinterface使用

2009-08-27 17:59:56

C#接口定义

2009-08-07 13:39:13

C#定义整型数组

2009-08-12 10:20:52

C#位运算符

2009-08-17 13:56:29

C#进度条的使用

2009-09-28 14:45:22

C#接口的定义

2010-01-25 10:41:59

C++数据类型

2009-08-14 15:23:10

C#使用ErrorPr

2009-08-17 17:36:08

C# 枚举

2009-08-18 10:30:30

C#枚举

2009-08-27 15:48:40

interfaceabstract cl

2009-08-19 16:42:41

C#如何使用XML

2009-08-13 13:29:04

C#结构体使用

2009-08-25 16:29:33

C#使用sqlserv
点赞
收藏

51CTO技术栈公众号