Calculate计算类; public class Calculate { private double x;//第一个数 public double X//封装字段 { get { return x; } set { x= value; } } private double y;//第二个数字段封装 public double Y { get { return y; } set { y = value; } } public double result; public virtual double Result()//利用多态实现简单工厂模式 { return result; } } public class Add : Calculate//派生加法类 { public override double Result()//重写基类中的方法,进行计算 { result = X + Y; return result; } } public class Sub : Calculate { public override double Result() { result = X - Y; return result; } } public class Mul : Calculate { public override double Result() { result = X * Y; return result; } } public class Div : Calculate { public override double Result() { result = X / Y; return result; } public class Mod : Calculate
{
public override double Result() { if (X == 0)
{
MessageBox.Show("分母不能为零");
}
result = X % Y;
return result;
}
}
public class calculate//运算类型 { public static Calculate Cal(string type)//派生一个为Calculate类型的Cal { Calculate cal = null;switch (type) { case "+": cal = new Add(); //加法 break; case "-": cal = new Sub(); break; case "*": cal = new Mul(); break; case "/": cal = new Div(); break;
case "%":
cal = new Mod();
break;
default: break; } return cal; } } }
WPF代码
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public static int question = 0;
public static int right = 0;
public static int t;
public static string type = "";
public static double result = 0;
public int n = 0;//文件中的数据
public MainWindow()
{
InitializeComponent();
}
private void txtresult_KeyDown(object sender, KeyEventArgs e)
{
Calculate cal=null;string typ = typ1.Text.ToString();//调用类成员 cal = calculate.Cal(typ); cal.X = Convert.ToDouble(txtone.Text); cal.Y= Convert.ToDouble(txttwo.Text); string result = Convert.ToString(cal.Result());
if (e.Key==Key.Enter)
{
if (txtresult.Text == cal.result.ToString())
{
righttxt.Visibility = Visibility.Visible;
righttxt.Text += txtone.Text + typ.Text + txttwo.Text +Li.Content+ txtresult.Text + "正确√" +""+ "
";
MessageBox.Show("回答正确");
txtone.Text = "";
txttwo.Text = "";
//txtthree.Text = "";
txtresult.Text = "";
typ.Text = "";
}
else
{
MessageBox.Show("回答错误");
faulttxt.Visibility = Visibility.Visible;
faulttxt.Text += txtone.Text + typ.Text + txttwo.Text + Li.Content + txtresult.Text + "错误×" + "" + "
";
txtone.Text = "";
txttwo.Text = "";
//txtthree.Text = "";
txtresult.Text = "";
typ.Text = "";
}
question++;
}
}
}
}