首页 > 编程技术 > csharp

浅析c# 接口

发布时间:2020-7-17 22:44

接口:

是指定一组函数成员而不是实现他们的引用类型。所以只能类喝啊结构来实现接口,在结成该接口的类里面必须要实现接口的所有方法

接口的特点:

继承于接口的类,必须要实现所有的接口成员

类可以继承,但是类只能继承一个基类,但是类可以继承多个接口

接口接口的定义用interface关键字,后面加接口的名称,名称通常是以字母I开头,接口不需要访问修符,因为接口都是供外部调用的,所以都是public的接口定义了所有类集成接口时应该应该遵循的语法合同,接口里面的内容是语法合同中“是什么”的部分,继承与接口的派生类中定义的是语法合同中“怎么做”的部分,接口中,只定义接口成员的声明,成员包括属性、方法、事件等。

因此在定义接口时候要注意如下几点:

1,例子;

//定义一个接口IParentInterface
    interface IParentInterface {

      void ParentInterface();//声明接口成员
    }

    class AllInterface : IParentInterface
    {

      public void ParentInterface() {

        Console.WriteLine("Hello");
      }
    }
    static void Main(string[] args)
    {
      AllInterface all = new AllInterface();
      all.ParentInterface();
    }

实现结果:

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

//定义一个接口IParentInterface
    interface IParentInterface {

      void ParentInterface();//声明接口成员
    }
    //IChildInterface
    interface IChildInterface {

      void ChildInterface();//声明接口成员
    }

    class AllInterface : IChildInterface
    {

      public void ParentInterface() {

        Console.Write("Hello" + " ");
      }

      public void ChildInterface() {

        Console.WriteLine("World");
      }
    }
    static void Main(string[] args)
    {
      AllInterface all = new AllInterface();
      all.ParentInterface();
      all.ChildInterface();
    }

实现结果:

以上就是浅析c# 接口的详细内容,更多关于c# 接口的资料请关注猪先飞其它相关文章!

标签:[!--infotagslink--]

您可能感兴趣的文章: