首页 > C#教程 阅读:18323

C#接口(interface)

通义灵码
接口可以看作是一个约定,其中定义了类或结构体继承接口后需要实现功能,接口的特点如下所示:
  • 接口是一个引用类型,通过接口可以实现多重继承;
  • 接口中只能声明"抽象"成员,所以不能直接对接口进行实例化;
  • 接口中可以包含方法、属性、事件、索引器等成员;
  • 接口名称一般习惯使用字母“I”作为开头(不是必须的,不这样声明也可以);
  • 接口中成员的访问权限默认为 public,所以我们在定义接口时不用再为接口成员指定任何访问权限修饰符,否则编译器会报错;
  • 在声明接口成员的时候,不能为接口成员编写具体的可执行代码,也就是说,只要在定义成员时指明成员的名称和参数就可以了;
  • 接口一旦被实现(被一个类继承),派生类就必须实现接口中的所有成员,除非派生类本身也是抽象类。

声明接口

C# 中声明接口需要使用 interface 关键字,语法结构如下所示:

public interface InterfaceName{
    returnType funcName1(type parameterList);
    returnType funcName2(type parameterList);
    ... ...
}

其中,InterfaceName 为接口名称,returnType 为返回值类型,funcName 为成员函数的名称,parameterList 为参数列表。

【示例】下面通过具体的示例演示一下接口的使用:
  1. using System;
  2.  
  3. namespace c.biancheng.net
  4. {
  5. public interface Iwebsite{
  6. void setValue(string str1, string str2);
  7. void disPlay();
  8. }
  9. public class Website : Iwebsite{
  10. public string name, url;
  11. public void setValue(string n, string u){
  12. name = n;
  13. url = u;
  14. }
  15. public void disPlay(){
  16. Console.WriteLine("{0} {1}", name, url);
  17. }
  18. }
  19. class Demo
  20. {
  21. static void Main(string[] args)
  22. {
  23. Website web = new Website();
  24. web.setValue("C语言中文网", "http://c.biancheng.net");
  25. web.disPlay();
  26. }
  27. }
  28. }
运行结果如下:

C语言中文网 http://c.biancheng.net

接口继承

在 C# 中,一个接口可以继承另一个接口,例如可以使用接口 1 继承接口 2,当用某个类来实现接口 1 时,必须同时实现接口 1 和接口 2 中的所有成员,下面通过一个示例来演示一下:
  1. using System;
  2.  
  3. namespace c.biancheng.net
  4. {
  5. public interface IParentInterface
  6. {
  7. void ParentInterfaceMethod();
  8. }
  9.  
  10. public interface IMyInterface : IParentInterface
  11. {
  12. void MethodToImplement();
  13. }
  14. class Demo : IMyInterface
  15. {
  16. static void Main(string[] args)
  17. {
  18. Demo demo = new Demo();
  19. demo.MethodToImplement();
  20. demo.ParentInterfaceMethod();
  21. }
  22. public void MethodToImplement(){
  23. Console.WriteLine("实现 IMyInterface 接口中的 MethodToImplement 函数");
  24. }
  25. public void ParentInterfaceMethod(){
  26. Console.WriteLine("实现 IParentInterface 接口中的 ParentInterfaceMethod 函数");
  27. }
  28. }
  29. }
运行结果如下:

实现 IMyInterface 接口中的 MethodToImplement 函数
实现 IParentInterface 接口中的 ParentInterfaceMethod 函数