首页 > Windows开发 > 详细

C# 接口

时间:2020-08-14 12:21:20      阅读:45      评论:0      收藏:0      [点我收藏+]

C# 接口(Interface)

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

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

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

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


定义接口:Interface.cs

接口使用 interface 关键字声明,它与类的声明类似。接口声明默认是 public 的。下面是一个接口声明的实例:

interface IInterface
{
    void MethodToImplement();
}

以上代码定义了接口 IInterface。通常接口命令以 I 字母开头,这个接口只有一个方法 MethodToImplement(),没有参数和返回值,当然我们可以按照需求设置参数和返回值。

值得注意的是,该方法并没有具体的实现。

接下来来实现以上接口:

public static void run()
        {
            Implementer imp = new Implementer();
            imp.MethodToImplement();
        }
        //实现接口
        class Implementer:IInterface
        {
            public void MethodToImplement()
            {
                Console.WriteLine("MethodToImplement call()");
            }
        }
        interface IInterface
        {
            void MethodToImplement();
        }

InterfaceImplementer 类实现了 IInterface 接口,接口的实现与类的继承语法格式类似:

class Implementer : IInterface

 

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


接口继承: 

以下实例定义了两个接口 IInterface 和 IParentInterface。

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

以下实例 IInterface 继承了 IParentInterface 接口,因此接口实现类必须实现 MethodToImplement() 和 ParentInterfaceMethod() 方法:

 public static void run()
        {
            Implementer imp = new Implementer();
            imp.MethodToImplement();
            imp.ParentInterfaceMethod();
        }
        //实现接口
        class Implementer:IInterface
        {
            public void MethodToImplement()
            {
                Console.WriteLine("MethodToImplement call()");
            }
            public void ParentInterfaceMethod()
            {
                Console.WriteLine(" ParentInterfaceMethod call()");
            }
        }
        //接口继承
        interface IInterface :IParentInterface
        {
            void MethodToImplement();
        }
        interface IParentInterface
        {
            void ParentInterfaceMethod();
        }
MethodToImplement call()
 ParentInterfaceMethod call()

 

C# 接口

原文:https://www.cnblogs.com/xqher/p/13501423.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!