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}

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

  • 相关阅读:
    Linux 安装 jdk 后 jps 出现问题/usr/jdk1.8.0_151/bin/jps: /lib/ld-linux.so.2: bad ELF interpreter: No such
    Jackson 注解
    Git 右键添加Git Bash
    No validator could be found for constraint
    rror querying database. Cause: java.sql.SQLException: null, message from server: "Host '192.168.30.1' is not allowed to connect to this MySQL server"
    Linux 安装 Mysql-5.7.23-linux-glibc2
    Promise
    PAT(B) 1094 谷歌的招聘(Java)
    PAT(B) 1074 宇宙无敌加法器(Java)
    PAT(B) 1078 字符串压缩与解压(Java)
  • 原文地址:https://www.cnblogs.com/wei1349/p/12905014.html
Copyright © 2011-2022 走看看