C# 接口 Interface(学习心得 22)

接口定义了所有类继承接口时应遵循的语法合同。

接口定义了语法合同 “是什么” 部分,派生类定义了语法合同 “怎么做” 部分。

接口定义了属性、方法和事件,这些都是接口的成员。

接口只包含了成员的声明。

成员的定义是派生类的责任。

接口提供了派生类应遵循的标准结构。

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

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

超级小白友好,讲解C#基础,每集5分钟轻松学习,拒绝从入门到放弃!

一、定义接口: MyInterface.cs

使用 interface 关键字声明,它与类的声明类似。

接口声明默认是 public 的。

例:

interface IMyInterface
{
    void MethodToImplement();
}

以上代码定义了接口 IMyInterface。

通常接口命令以 I 字母开头。

这个接口只有一个方法 MethodToImplement(),没有参数和返回值,当然我们可以按照需求设置参数和返回值。

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

二、接口实现:InterfaceImplementer.cs

例:

using System;

interface IMyInterface
{
        // 接口成员
    void MethodToImplement();
}

class InterfaceImplementer : IMyInterface // 继承接口
{
    static void Main()
    {
        InterfaceImplementer iImp = new InterfaceImplementer(); // 类的实例化
        iImp.MethodToImplement(); // 类的方法调用
    }

    public void MethodToImplement() // 接口方法的具体实现
    {
        Console.WriteLine("MethodToImplement() called.");
    }
}

运行结果:

MethodToImplement() called.

三、接口继承: InterfaceInheritance.cs

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

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

using System;

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.");
    }
}

运行结果:

MethodToImplement() called.
ParentInterfaceMethod() called.
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值