1.计算类
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 封装1 { public class Calcuater { private int numberA; private int numberB; public int NumberA { get { return numberA; } set {numberA=value;} } public int NumberB { get { return numberB; } set { numberB = value; } } public virtual int getresult() { int result=0; return result; } } public class Add : Calcuater { public override int getresult() { int result = 0; result = NumberA + NumberB; return result; } } public class Sub : Calcuater { public override int getresult() { int result = 0; result = NumberA - NumberB; return result; } } public class Mul : Calcuater { public override int getresult() { int result = 0; result = NumberA * NumberB; return result; } } public class Div : Calcuater { public override int getresult() { int result = 0; if (NumberB == 0) { throw new Exception("除数不能为零!"); } else { result = NumberA / NumberB; } return result; } } }
2.定义环境
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 封装1 { class factory { public static Calcuater create(string operte) { Calcuater oper=null; switch (operte) { case "+": oper = new Add(); break; case "-": oper = new Sub(); break; case "*": oper = new Mul(); break; case "/": oper = new Div(); break; } return oper; } } }
3.form1代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace 封装1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { chuti(); } private void textBox3_KeyDown(object sender, KeyEventArgs e) { int a =int.Parse( textBox1.Text); int b = int.Parse(textBox2.Text); string c = label1.Text; if (e.KeyCode == Keys.Enter) { Calcuater calas = factory.create(c); calas.NumberA = a; calas.NumberB = b; int reat = calas.getresult(); if (textBox3.Text == reat.ToString()) { MessageBox.Show("回答正确!"); } else { MessageBox.Show("回答错误!"); } textBox3.Clear(); chuti(); } } private void chuti() { Random random = new Random(); textBox1.Text = random.Next(0, 100).ToString(); textBox2.Text = random.Next(0, 100).ToString(); string[] operte = new string[] { "+", "-", "*", "/" }; label1.Text = operte[new Random().Next(0, 4)]; } } }