类的使用-回顾

一、类的使用

    #region 1、类的本质:类是一种抽象的数据类型,是对一类对象的统一描述(具有相同特性的事物归档一类)
    class A
    {
        public string Name { get; set; }
        public string ActionName() { return "行为!"; }
    }
    #endregion

    #region 2、接口的本质:定义一套规范,接口更多的是在系统架构设计方法发挥作用,主要用于定义模块之间的通信契约。
    interface IExample
    {
        //注意: 与Java不同的是,C#中接口声明不能添加任何修饰符,默认是public   

        //定义方法   
        void F(int value);
        //定义属性   
        string P { get; set; }
        //定义索引指示器   
        string this[int index] { get; set; }
        //定义事件   
        event EventHandler E;
    }
    class InterfaceName : IExample
    {
        public void F(int value) { throw new NotImplementedException(); }
        public string P { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
        public string this[int index] { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }

        public event EventHandler E;
    }


    #endregion


    #region 3、抽象类的本质:应用上抽象类在代码实现方面发挥作用,可以实现代码的重用
    //1、抽象类不能被实例化只能被继承,抽象方法没有实现的方法抽象类的子类必须实现每个抽象方法。
    //抽象动物类,声明抽象方法Shout(),注意抽象方法没有方法体
    abstract class Animal
    {
        public abstract void Shout();
    }
    //猫类 继承动物类,覆盖抽象Shout()方法
    class Cat : Animal
    {
        public override void Shout()
        {
            Trace.WriteLine("喵喵!");
        }
    }
    #endregion

    #region 4、virtual 关键字用于在基类中修饰方法
    class Apple
    {
        //加关键字virtual,将函数标记为虚方法
        public virtual void SayHello()//将函数标记为虚方法
        {
            Console.Write("Hello!");
        }
    }
    //继承基类Apple
    class Orange : Apple
    {
        public override void SayHello()//在派生类中重写
        {
            base.SayHello();
        }
    }
    #endregion
原文地址:https://www.cnblogs.com/fger/p/13463521.html