zoukankan      html  css  js  c++  java
  • 接口、抽象类、抽象方法、虚方法总结

    一、接口

      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、可以在派生类中覆写,也可以不覆写;

  • 相关阅读:
    设计模式- 模板方法模式
    什么是Coded UI
    请介绍WCF服务
    我的WCF之旅(1):创建一个简单的WCF程序
    7.3 Models -- Creating And Deleting Records
    7.2 Models -- Defining Models
    7.1 Models -- Introduction
    6.3 Controllers -- Managing Dependencies Between Controllers
    6.2 Controllers -- Representing Multipe Models
    6.1 Controllers -- Introduction
  • 原文地址:https://www.cnblogs.com/mahoumei/p/6881754.html
Copyright © 2011-2022 走看看