zoukankan      html  css  js  c++  java
  • C#--接口Interface(转载)

    接口定义了属性、方法和事件,这些都是接口的成员。接口只包含了成员的声明。成员的定义是派生类的责任。接口提供了派生类应遵循的标准结构。

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

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

    1.接口用于描述一组类的公共方法/公共属性. 它不实现任何的方法或属性,只是告诉继承它的类至少要实现哪些功能,继承它的类可以增加自己的方法.

    2.使用接口可以使继承它的类: 命名统一/规范,易于维护.比如: 两个类 "狗"和"猫",如果它们都继承了接口"动物",其中动物里面有个方法Behavior(),那么狗和猫必须得实现Behavior()方法,

    并且都命名为Behavior这样就不会出现命名太杂乱的现象.如果命名不是Behavior(),接口会约束即不按接口约束命名编译不会通过.

    3.提供永远的接口。 当类增加时,现有接口方法能够满足继承类中的大多数方法,没必要重新给新类设计一组方法,也节省了代码,提高了开发效率.

    //公共接口: "动物"
    public Interface IAnimal
    {
      int EyeNumber;
      private void Behavior();//行为方法,描述各种动物的特性
    }
    //类: 狗 public Dog : IAnimal {   string ActiveTime = "白天";   private void Behavior()   {     Console.Write("我晚上睡觉,白天活动");   } }
    //类: 猫 public Cat: IAnimal {   string ActiveTime = "夜晚";   private void Behavior()   {     Console.Write("我白天睡觉,晚上活动");   } }
    //简单的应用: public static Main() {   Dog myDog = new Dog();   myDog.Behavior(); //输出: "我晚上睡觉,白天活动"   Cat myCat = new Cat();   myCat.Behavior(); //输出: "我白天睡觉,晚上活动" }

      

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

    以下实例 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.

    转载于:https://www.runoob.com/csharp/csharp-interface.htmlhttps://www.cnblogs.com/yoyolm2014/p/9431387.html

  • 相关阅读:
    10:简单密码
    08:字符替换
    07:配对碱基链
    05:输出亲朋字符串
    18:等差数列末项计算
    09:密码翻译
    用最通俗的话说23种设计模式之代理模式
    Android学习之 UI效果
    精确到时分秒的jQuery插件例子
    Eclipse 常用快捷键
  • 原文地址:https://www.cnblogs.com/mexihq/p/12503573.html
Copyright © 2011-2022 走看看