(三十三)C#编程基础复习——C#接口(interface)

发布时间 2023-12-18 11:13:31作者: 代号六零一

接口可以看做是一个约定,其中定义了类或结构体继承接口后需要实现功能,接口的特点如下:

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

一、声明接口

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

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

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

namespace _030
{
    public interface Iwebsite//定义一个接口
    {
        void setValue(string str1, string str2);
        void disPlay();
    }
    public class Website:Iwebsite//定义一个类实现接口
    {
        public string name, url;
        public void setValue(string n,string u)
        {
            name = n;
            url = u;
        }
        public void disPlay()
        {
            Console.WriteLine("{0} {1}",name,url);
        }
    }
    internal class Program
    {
        static void Main(string[] args)
        {
            Website web = new Website();
            web.setValue("C#中文网", "http://c.biancheng.net");
            web.disPlay();
            Console.ReadKey();
        }
    }
}

二、接口继承

在C#中,一个接口可以继承另一个接口,例如可以使用接口1继承接口2,当用某个类来实现接口1时,必须同时实现接口1和接口2中的所有成员,例子如下:

namespace _031
{
    public interface IParentInterface//定义父类接口
    {
        void ParentInterfaceMethod();
    }
    public interface IMyInterface:IParentInterface//继承父类接口
    {
        void MethodToImplement();
    }
    internal class Program:IMyInterface//实现接口
    {
        static void Main(string[] args)
        {
            Program demo = new Program();
            demo.MethodToImplement();
            demo.ParentInterfaceMethod();
        }
        public void MethodToImplement()
        {
            Console.WriteLine("实现IMyInterface接口中的MethodToImplement函数");

        }
        public void ParentInterfaceMethod()
        {
            Console.WriteLine("实现IParentInterface接口中的ParentInterfaceMethod函数");
        }
    }
}