C# 接口(Interface)

来源:互联网 发布:学生空间七天网络app 编辑:程序博客网 时间:2024/06/04 19:37

C#接口

接口定义了所有类继承接口时应准讯的语法合同。接口定义了语法合同是什么部分,派生类定义了语法合同怎么做的部分

接口定义了属性、方法和时间,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。

接口使得实现接口的类或结构在形式上保持一致。

抽象类在某种程度上与接口类似,但是,他他们大多只是在当只有少数方法由基类声明由派生类实现时。

接口语法的定义实例代码如下:

//C#接口的语法using System;interface IMyInterface {    void MethodImplement();}class InterfaceImplementer:IMyInterface{    public static viod Main(string[] args)    {        InterfaceImplementer im = new InterfaceImplementer();        im.MethodImplement();    }     public void MethodImplement()    {        Console.WriteLine("MethodImplement() called");    }}

继承接口后,我们需要实现接口的方法,方法名必须与接口定义的方法名一致。


接口继承

如果一个接口继承其他的接口,那么实现类或结构需要实现所有接口的成员。

示例代码如下:

using System;interface IParentInterface{    void ParentInterfaceMethod();}interface IMyInterface:IParentInterface{    void MethodToImplement();}class InterfaceImplementer:IMyInterface{    static void Main()    {        InterfaceImplementer Im = new InterfaceImplementer()        Im.MethodToImplement();        Im.ParentInterfaceMethod();    }    //实现继承接口的方法    public void MethodToImplement()    {        Console.WriteLine("MethodToImplement() called")    }    //实现继承接口的继承接口的方法    public void ParentInterfaceMethod()    {        Console.WriteLine("ParentInterfaceMethod() called")    }}


原创粉丝点击