zoukankan      html  css  js  c++  java
  • 学习C#接口

    学习C#接口(interface)

    以下均为在菜鸟教程中学习的笔记


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

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

    成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。

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

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


    定义接口:

    接口使用interface关键字声明。它与类的声明类似。接口声明默认时public的。

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

    运用的实例:

    interface IMyInterface
        {
            //接口成员
            void MethodToImplement();
        }
        class Program : IMyInterface
        {
            //定义接口里成员方法的成员
            public void MethodToImplement()
            {
                Console.WriteLine("1");
            }
        }
        class test
        {
            static void Main()
            {
                Program p = new Program();
                p.MethodToImplement();
            }
        }
    

    结果:

    1
    

    接口继承

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

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

    实例:

    interface IParentInterface
        {
            void ParentInterfaceMethod();
        }
        interface IMyInterface:IParentInterface
        {
            //接口成员
            void MethodToImplement();
        }
    
        class Program : IMyInterface
        {
            //定义接口里成员方法的成员
            public void MethodToImplement()
            {
                Console.WriteLine("1");
            }
            public void ParentInterfaceMethod()
            {
                Console.WriteLine("2");
            }
        }
        class test
        {
            static void Main()
            {
                Program p = new Program();
                p.MethodToImplement();
                p.ParentInterfaceMethod();
            }
        }
    

    结果:

    1
    2
    

    注意:

    接口不能用public abstract等修饰。

    接口可以定义属性。如 string color{get;set}

    实现接口时,必须与接口的格式一致且实现接口里的所有方法

  • 相关阅读:
    微信小程序之授权 wx.authorize
    微信小程序之可滚动视图容器组件 scroll-view
    纯 CSS 利用 label + input 实现选项卡
    Nuxt.js + koa2 入门
    koa2 入门(1)koa-generator 脚手架和 mongoose 使用
    vue 自定义指令
    时运赋
    WEBGL 2D游戏引擎研发系列 第一章 <新的开始>
    EasyUI特殊情况下的BUG整理
    数字时钟DigClock
  • 原文地址:https://www.cnblogs.com/wei1349/p/12905014.html
Copyright © 2011-2022 走看看