C# 抽象类和接口详解

news2024/10/6 14:36:28

参考视频链接:https://www.bilibili.com/video/BV13b411b7Ht?p=27&vd_source=10065785c7e10360d831474364e0d3e3
代码的进化与重构,从基本代码的讲解到逐步抽象成抽象类和接口。

文章目录

  • 最初定义
  • 利用继承改进
  • 对方法进一步改进
  • 利用虚函数进行改进
  • 利用抽象进行改进
  • 利用接口进行改进
  • 最后给出最终的完整代码:

最初定义

最初定义两个类Car 和 Truck

namespace InterfaceAPPLication
{
    class Car
    {
        public void Run()
        {
            Console.WriteLine("Car is Running");
        }
        public void Stop() 
        {
            Console.WriteLine("Stopped");
        }
    }

    class Truck
    {
        public void Run()
        {
            Console.WriteLine("Truck is Running");
        }
        public void Stop()
        {
            Console.WriteLine("Stopped");
        }
    }
}

利用继承改进

两个类具有重复的代码Stop()方法,不符合代码不重复出现的规则,对代码进行改进,将两个类继承自一个类 Vehicle

namespace InterfaceAPPLication
{
    class Vehcile
    {
        public void Stop()
        {
            Console.WriteLine("Stopped");
        }
    }
    class Car:Vehcile
    {
        public void Run()
        {
            Console.WriteLine("Car is Running");
        }
    }

    class Truck
    {
        public void Run()
        {
            Console.WriteLine("Truck is Running");
        }
    }
}

对方法进一步改进

继续观察Run方法,对Run方法进行改进:

namespace InterfaceAPPLication
{
    class Vehcile
    {
        public void Stop()
        {
            Console.WriteLine("Stopped");
        }

        public void Run(string type)
        {
            if (type == "Car")
            {
                Console.WriteLine("Car is Running");
            }else if(type == "Truck")
            {
                Console.WriteLine("Truck is Running");
            }
           
        }
    }
    class Car:Vehcile
    {
        
    }

    class Truck:Vehcile
    {
       
    }
}

利用虚函数进行改进

但是当有新的类从Vehcile派生的话,就需要多Vehicle.Run(string type)函数体进行扩充,不符合设计原则中的封闭原则。替代方式,使用virtual虚函数修饰Run方法,派生类对Run方法进行重写。

namespace InterfaceAPPLication
{
    class Vehcile
    {
        public void Stop()
        {
            Console.WriteLine("Stopped");
        }

        public virtual void Run(string type)
        {
            Console.WriteLine("Vehcile is Running");
        }
    }
    class Car:Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Car is Running");
        }
    }

    class Truck:Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Truck is Running");
        }
    }
}

利用抽象进行改进

基类Vehicle的Run方法被派生类重新实现,所以Run方法的函数体是没有意义的,所以可以修改为abstract方法,同时 Vehicle类为抽象类;

namespace InterfaceAPPLication
{
    abstract class Vehcile
    {
        public void Stop()
        {
            Console.WriteLine("Stopped");
        }

        public abstract void Run(string type);
    }
    class Car:Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Car is Running");
        }
    }

    class Truck:Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Truck is Running");
        }
    }
}

Vehcile抽象类包含的方法不全是抽象方法,当一个抽象类全部都是抽象方法的时候,IVechile类就是一个全是抽象方法的类 。可以看到Vehcile :继承IVechile,其中重写了 Filled() 和 Stop()方法,没有重写Run(string type)方法,不需要声明,默认继承了,然后Run(string type)在Car和Truck类中实现。

 abstract class IVechile
    {
        public abstract void Filled();
        public abstract void Run(string type);
        public abstract void Stop();
    }
    abstract class Vehcile : IVechile
    {
        public override void Stop()
        {
            Console.WriteLine("Stopped");
        }
        public override void Filled()
        {
            Console.WriteLine("Pay and Filled");
        }

    }
    class Car : Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Car is Running");
        }
    }

    class Truck : Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Truck is Running");
        }
    }

利用接口进行改进

IVechile类就是一个全是抽象方法的类 ,

 abstract class IVechile
    {
        public abstract void Filled();
        public abstract void Run(string type);
        public abstract void Stop();
    }

抽象类的抽象方法需要被派生类实现,所以默认是public abstract, 改为接口后方法就不需要修饰符了:(接口的命名方式大写英文字母 I+name)

 interface IVechile
    {
        void Filled();
        void Stop();
        void Run(string type);
    }

注意,在对接口中方法进行实现的时候,没有实现的方法,需要在抽象类中注明是待实现的抽象方法

 interface IVechile
    {
        void Filled();
        void Stop();
        void Run(string type);
    }
    abstract class Vehcile : IVechile
    {
        public  void Stop()
        {
            Console.WriteLine("Stopped");
        }
        public  void Filled()
        {
            Console.WriteLine("Pay and Filled");
        }
        abstract public void Run(string type);
    }

最后给出最终的完整代码:

using System;
using System.Collections;
using System.Data;

namespace InterfaceAPPLication
{

    interface IVechile
    {
        void Filled();
        void Stop();
        void Run(string type);
    }
    abstract class Vehcile : IVechile
    {
        public  void Stop()
        {
            Console.WriteLine("Stopped");
        }
        public  void Filled()
        {
            Console.WriteLine("Pay and Filled");
        }
        abstract public void Run(string type);
    }
    class Car : Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Car is Running");
        }
    }

    class Truck : Vehcile
    {
        public override void Run(string type)
        {
            Console.WriteLine("Truck is Running");
        }
    }

    class Executer
    {
        static void Main(string[] args)
        {
            Vehcile car = new Car();
            car.Run("Car");
            car.Stop();

            Vehcile truck = new Truck();
            truck.Run("Truck");
            truck.Stop();

        }
    }
}

运行结果:
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/768722.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

设计模式结合场景(1)——支付场景(策略+工厂+模板)

ps:以下示例仅供参考,设计模式只是一种思想,至于怎么千变万化就看大家了。 一、背景 面试官:你们项目的支付场景用了哪些设计模式,为什么要这么做? 二、方案 使用策略模式定义不同支付方式的具体支付策略&…

[深度学习实战]基于PyTorch的深度学习实战(上)[变量、求导、损失函数、优化器]

目录 一、前言二、深度学习框架——PyTorch2.1 PyTorch介绍2.2 Python安装详解2.3 PyTorch安装详解 三、变量四、求导五、损失函数5.1 nn.L1Loss5.2 nn.SmoothL1Loss5.3 nn.MSELoss5.4 nn.BCELoss5.5 nn.CrossEntropyLoss5.6 nn.NLLLoss5.7 nn.NLLLoss2d 六、优化器Optim 6.1 …

ARM Coresight 系列文章 8 - ARM Coresight 通过 APBIC 级联使用

文章目录 APBIC 回顾APBIC 级联 上篇文章:ARM Coresight 系列文章 7 - ARM Coresight 通过 AHB-AP 访问 异构 cpu 内部 coresight 组件 APBIC 回顾 APBIC 可以连接一个或者多个APB BUS masters, 例如连接一个 APB-AP 组件和带有 APB 接口的 Processor&…

Java源码规则引擎:jvs-rules数据扩展及函数配置说明

jvs-rules数据拓展节点 数据拓展是数据可视化加工过程中的重要工具,它核心的作用是对原有数据表进行加工扩展,实现功能如下图所示 函数配置操作过程 操作说明 1、拖动数据拓展字段,并将字段拓展与之前的历史节点连接起来,点击数…

浅谈linux前台进程与后台进程同步异步执行的理解

最近书上看到前台进程以及后台进程的定义,有点令人费解。 linux终端输入一条命令,创建一个子进程运行这条命令,在这条命令进程执行完之前,终端shell都无法接收新的一条命令;只有这条命令运行结束后,当前终…

Vue项目实现在线预览pdf,并且可以批量打印pdf

最近遇到一个需求,就是要在页面上呈现pdf内容,并且还能用打印机批量打印pdf,最终效果如下: 当用户在列表页面,勾选中两条数据后,点击“打印表单”按钮之后,会跳到如下的预览页面: 预览页面顶部有个吸顶的效果,然后下方就展示出了2个pdf文件对应的内容,我们接着点击“…

Vsiual Stdio 生成动态链接库 / 命令行CMD工具打不开 / 64和32位动态链接库生成 dll

打开vistual studio,选择目标文件夹。 菜单栏选择工具->命令行->开发者命令提示 通过 这种方法打开的编译器版本是 32位(x86)的 64位的编译器通过以下方法打开 修改文件路径 1)Cd 路径 2) 盘符: 输入命令行代码 cl /c Se…

SpringBoot整合SpringSecurity+JWT

SpringBoot整合SpringSecurityJWT 整合SpringSecurity步骤 编写拦截链配置类,规定security参数拦截登录请求的参数,对该用户做身份认证。通过登录验证的予以授权,这里根据用户对应的角色作为授权标识。 整合JWT步骤 编写JWTUtils&#xf…

精智达在科创板上市:募资约11亿元,深创投等为其股东

7月18日,深圳精智达技术股份有限公司(下称“精智达”,SH:688627)在上海证券交易所科创板上市。本次上市,精智达的发行价为46.77元/股,发行数量为2350.2939万股,募资总额为10.99亿元,…

封装cpp-httplib成dll包,为老项目提供http网络支持

项目介绍: 公司内某些老的项目不支持https或者http1.1的一些新功能,需要开发对应的SDK供其调用,以便维护老项目。 第一步:下载cpp-httplib 点击这里去下载最新的代码:mirrors / yhirose / cpp-httplib GitCode 直接下…

QT:问题、解决与原因

在这里记录一些自己遇到的在QT开发上面的小问题和tips 目录 QComboBox 设置qss样式不生效qt按钮设置点击释放效果实现效果 QComboBox 设置qss样式不生效 我设置的样式是: box->setStyleSheet("QComboBox {""border: none;""padding:…

适用于 Type-C接口PD应用的智能二极管保护开关

日前,集设计、研发、生产和全球销售一体的著名功率半导体、芯片及数字电源产品供应商Alpha and Omega Semiconductor Limited(AOS, 纳斯达克代码:AOSL) 推出一款采用理想二极管运作进行反向电流保护的新型Type-C PD 高压电源输入保护开关。AOZ13984DI-02…

上市公司前端开发规范参考

上市公司前端开发规范参考 命名规则通用约定文件与目录命名HTML命名CSS命名JS命名 代码格式通用约定HTML格式CSS格式JS格式注释 组件组件大小单文件组件容器组件组件使用说明Prop指令缩写组件通讯组件的挂载和销毁按需加载第三方组件库的规定 脚手架使用规范移动端脚手架PC端脚…

Linux下安装Elasticsearch以及ES-head插件

Linux下安装ElasticSearch以及ES-head插件 安装Elasticsearch 由于Elasticsearch客户端版本和ElasticSearch版本有对应关系,所以建议安装之前先考虑安装哪个版本的ElasticSearch。 ElasticSearch、Spring Data Elasticsearch、SpringBoot、Spring版本对应关系 安…

OpenCV for Python 学习第五天:图片属性的获取

上一篇博文当中,我们学习了如何获取图片的通道,我们了解了通道的分离方法split()和通道的组合方法merge()。那么我们今天就来对图片的属性做一个深入的了解。 文章目录 图片属性OpenCV中属性介绍图片属性的获取 图片属性 图片属性是指描述和定义一张图片…

爬虫与反爬虫的攻防对抗

一、爬虫的简介 1 概念 爬虫最早源于搜索引擎,它是一种按照一定的规则,自动从互联网上抓取信息的程序,又被称为爬虫,网络机器人等。按爬虫功能可以分为网络爬虫和接口爬虫,按授权情况可以分为合法爬虫和恶意爬虫。恶…

【NLP】从预训练模型中获取Embedding

从预训练模型中获取Embedding 背景说明下载IMDB数据集进行分词下载并预处理GloVe词嵌入数据构建模型训练模型并可视化结果结果对比其他代码 在NLP领域中,构建大规模的标注数据集非常困难,以至于仅用当前语料无法有效完成特定任务。可以采用迁移学习的方法…

hbuilder创建基于vue2的uniapp小程序项目

参考vant官网:https://vant-contrib.gitee.io/vant/v3/#/zh-CN/quickstart#an-zhuang官网 参考别人博客:https://www.yii666.com/blog/465379.html 1.创建项目 1.1 hbuilder进去右上角点击文件–新建–项目 1.2 vue2项目如下图 2.安装依赖 2.1 2.2…

Linux搭建SVN环境(最新版)

最新版本号(svn-1.14) https://opensource.wandisco.com/centos/7 更新版本库 sudo tee /etc/yum.repos.d/wandisco-svn.repo <<-EOF [WandiscoSVN] nameWandisco SVN Repo baseurlhttp://opensource.wandisco.com/centos/$releasever/svn-1.14/RPMS/$basearch/ enabled…

TypeScript 学习笔记(七):条件类型

条件类型 TS中的条件类型就是在类型中添加条件分支&#xff0c;以支持更加灵活的泛型&#xff0c;满足更多的使用场景。内置条件类型是TS内部封装好的一些类型处理&#xff0c;使用起来更加便利。 一、基本用法 当T类型可以赋值给U类型时&#xff0c;则返回X类型&#xff0c…