接口、抽象类、抽象方法、虚方法总结

一、接口

  1、定义

    1.1、访问修饰符 interface 接口名{成员可以为属性、方法、事件、索引器}

    1.2、示例代码    

public delegate void DelInfo(int Id);
    public interface IInformation
    {
        //属性
        int Id { get; set; }

        int[] ArrayInt { get; set; }
        //方法
        void IGetInfo();
        //事件
        event DelInfo IDelInfo;
        //索引器
        long this[int index] { get; set; }
    }

  2、特点

    2.1、接口内的成员都不能被实现;

    2.2、接口可以被多继承;

    2.3、接口不能被实例化;

    2.4、接口中不能包含常量、字段(域)、构造函数、析构函数、静态成员;

 二、抽象类、抽象方法

  1、定义

    1.1、访问修饰符 abstract class 抽象类名

    1.2、示例代码

public delegate void DelInformation(int id);
    public abstract class BaseInformation
    {
        //字段
        private int _id;
        //属性
        public int Id { get { return _id; } set { _id = value; } }
        //事件
        event DelInformation EventDelInformation;
        //普通方法
        public void GetInformation(int id) { Console.WriteLine(id); if (this.EventDelInformation != null) this.EventDelInformation(1); }
        //虚方法  
        public virtual int GetId() { return Id; }
        //抽象方法
        public abstract int GetInfo();
        //索引器
        //可容纳100个整数的整数集
        private long[] arr = new long[100];
        //声明索引器
        public long this[int index]
        {
            get
            { //检查索引范围
                if (index < 0 || index >= 100)
                {
                    return 0;
                }
                else
                {
                    return arr[index];
                }
            }
            set
            {
                if (!(index < 0 || index >= 100))
                {
                    arr[index] = value;
                }
            }
        }
    }

    2、特点

      2.1、和接口一样不能被实例化;

      2.2、如果包含抽象方法,类必须为抽象类;

      2.3、具体派生类必须覆盖基类的抽象方法;

      2.4、抽象类中的虚方法可以被覆写也可以不覆写;

      2.5、抽象派生类可以覆盖基类的抽象方法,也可以不覆盖;

  三、虚方法

    1、定义

      1.1、在方法前加上virtual;

      1.2、示例代码

  

public virtual void GetId()
        {
            Console.WriteLine("");
        }

    2、特点

      2.1、要有方法体;

      2.2、可以在派生类中覆写,也可以不覆写;

原文地址:https://www.cnblogs.com/mahoumei/p/6881754.html