首页 > 代码库 > 超级简单版多态计算器
超级简单版多态计算器
个人笔记学习黑马四期
一、编写一个操作父类
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 多态计算器{ /// <summary> /// 计算父类 /// </summary> class Operation { public int NumA { get; set; } public int NumB { get; set; } public Operation(int numA, int numB) { this.NumA = numA; this.NumB = numB; } public virtual int GetRes() { return 0; } }}
二、写出加减乘除的类,继承于操作类
加
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 多态计算器{ class Add:Operation { public Add(int numA, int numB) : base(numA, numB) { } public override int GetRes() { return base.NumB+NumA; } }}
减
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 多态计算器{ class Jian:Operation { public Jian(int numA, int numB) : base(numA, numB) { } public override int GetRes() { return base.NumA-NumB; } }}
乘
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 多态计算器{ class Ji:Operation { public Ji(int numA, int numB) : base(numA, numB) { } public override int GetRes() { return base.NumA*NumB; } }}
除
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 多态计算器{ class Div:Operation { public Div(int numA, int numB) : base(numA, numB) { } public override int GetRes() { return base.NumA/NumB; } }}
三、写Main
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using 多态计算器;namespace C09多态计算器{ class Program { static void Main(string[] args) { //多态是基于继承 //找父类 //找子类的共同方法 //找每个子类的同1个方法,具有不同的实现 Console.WriteLine("请输入第一个数字"); int numA = int.Parse(Console.ReadLine()); Console.WriteLine("请输入第二个数字"); int numB = int.Parse(Console.ReadLine()); // Console.WriteLine("请输入操作符:1.加 2.减 3.乘 4.除"); string opt = Console.ReadLine(); Operation operation=null; switch (opt) { case "1": operation=new Add(numA,numB); break; case "2": operation =new Jian(numA,numB); break; case "3": operation=new Ji(numA,numB); break; case "4": operation =new Div(numA,numB); break; } Console.WriteLine(operation.GetRes()); Console.ReadKey(); } }}
就好了
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。