C# 认识 接口

一.什么是接口

C#接口中包含方法、属性、索引器和事件的声明,但常用的接口中一般就是方法和属性,然而接口中并没有方法的具体实现代码(不能提供任何成员实现),只有方法的返回类型和方法名。一个类实现了某个接口,则必须在类中包含接口中所有方法的实现代码,换句话说就是,继承自接口的类中必须包含接口中函数的实现代码。

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

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

二.接口有啥用

可以对继承自接口的类起到约束作用,

通过接口,可以对方法进行统一管理,避免在每一种类型中重复定义这些方法

三.定义一个接口

接口使用 interface 关键字声明,后面加接口的名称,名称通常以字母 I 开头 ,它与类的声明类似。

interface IMyInterface
{
    void MethodToImplement();
}

1、不需要任何访问修饰符,默认是 public (因为接口是供外部调用的 )

2、接口中除了定义方法外,还可以包含属性(有get和set的方法如string color { get ; set ; }这种)、事件、索引器、或者这四类的任意组合。但是接口不能包含字段、运算符重载、实例构造函数、析构函数。

3、接口中不能使用 static 关键字

4、不能被实例化成对象

扫描二维码关注公众号,回复: 6816218 查看本文章

四.继承接口

继承于接口的类,必须实现接口定义中的所有方法。继承方法于类是一样的只要使用 即可

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

interface IParentInterface
{
    void ParentInterfaceMethod();
}

interface IMyInterface : IParentInterface
{
    void MethodToImplement();
}

class InterfaceImplementer : IMyInterface
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer();
        iImp.MethodToImplement();
        iImp.ParentInterfaceMethod();
    }

    public void MethodToImplement()
    {
        Console.WriteLine("MethodToImplement() called.");
    }

    public void ParentInterfaceMethod()
    {
        Console.WriteLine("ParentInterfaceMethod() called.");
    }
}

猜你喜欢

转载自www.cnblogs.com/Tanghongchang/p/6715395.html