-
C#教程之C#教程之C#实现多态之接口
本站最新发布 C#从入门到精通
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
试听地址 https://www.xin3721.com/eschool/CSharpxin3721/
一、什么是接口?
接口就是一种规范协议,约定好遵守某种规范就可以写通用的代码。
定义了一组具有各种功能的方法(只是一种能力,没有具体实现,就像抽象方法一样,“光说不做”)。
理解:内存该做成什么样的:电压多少,插线多少,这是一种国际规范,是接口。而,内存这个东西具体生产出来了,就是实现接口。不管是什么品牌的电脑,买来内存都能用,这是多态。
接口可以包含:方法、属性、索引器,事件。 其实都是方法。
接口中的所有成员,都不能写任何访问修饰符,默认是public。
接口的成员,子类必须实现。
二、接口的作用。
接口可以实现多继承。
接口解决了不同类型之间的多态问题,比如鱼和船不是同一种类型,但是都能在水里“游泳”,只是方式不同,所以可用接口。(下面实例最后一步,逻辑上,car不属于person类,但是仍然可以实现多态)
三、实例。
我想登记每个国家的人,可以使用方法重载,传入不同类型的参数,实现对应的方法,但是会写很多。 而且如果要添加一个国家的人,得改代码,可扩展性差。
class Program { static void Main(string[] args) { Chinese chinese = new Chinese(); DengJi(chinese); American american = new American(); DengJi(american); } public static void DengJi(Chinese chinese) { chinese.Show(); } public static void DengJi(American american) { american.Show(); } } class Chinese { public void Show() { Console.WriteLine("中国人,18岁"); } } class American { public void Show() { Console.WriteLine("美国人,19"); } }
优化一:通过继承实现多态, 用参数的时候用父类,具体操作看父类中存储的对象。------ 提取出父类Person,使用虚方法或者抽象方法。因为Person不需要实例化,所以我用抽象类。
class Program { static void Main(string[] args) { Chinese chinese = new Chinese(); DengJi(chinese); American american = new American(); DengJi(american); } public static void DengJi(Person person) { person.Show(); } } public abstract class Person { public abstract void Show(); } class Chinese:Person { public override void Show() { Console.WriteLine("中国人,18岁"); } } class American:Person { public override void Show() { Console.WriteLine("美国人,19"); } }
优化二:如果我要登记一辆车,车继承了Person类,不符合逻辑,但我又要实现多态,任何东西都能登记。所以我选择用接口。
class Program { static void Main(string[] args) { Chinese chinese = new Chinese(); DengJi(chinese); Car car = new Car(); car.Show(); } public static void DengJi(IShowInfo person) { person.Show(); } } public interface IShowInfo { void Show(); } public abstract class Person:IShowInfo { public abstract void Show(); } class Chinese:Person { public override void Show() { Console.WriteLine("中国人,18岁"); } } class American:Person { public override void Show() { Console.WriteLine("美国人,19"); } } class Car :IShowInfo { public void Show() { Console.WriteLine("本田,2.0t"); } }
这样一来,无论什么东西,只要继承了接口,都能登记。
栏目列表
最新更新
如何使用OS模块中的stat方法
Python os 模块
seek() 方法
python打开文件实例1
Python写入文件
什么是流?
文件操作如何进制逐行读取
Python相对路径
with创建临时运行环境
Python文件操作
.Net Standard(.Net Core)实现获取配置信息
Linux PXE + Kickstart 自动装机
Shell 编程 基础
Shell 编程 条件语句
CentOS8-网卡配置及详解
Linux中LVM逻辑卷管理
1.数码相框-相框框架分析(1)
Ubuntu armhf 版本国内源
Linux中raid磁盘阵列
搭建简易网站
access教程之Access简介
mysql 安装了最新版本8.x版本后的报错:
Mysql空间数据&空间索引(spatial)
如何远程连接SQL Server数据库的图文教程
复制SqlServer数据库的方法
搜索sql语句
sql中返回参数的值
sql中生成查询的模糊匹配字符串
数据定义功能
数据操作功能