fengzhuang.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class fengzhuang
{
private double a = 0;
private double b = 0;
public double A
{
get { return a; }
set { a = value; }
}
public double B
{
get { return b; }
set { b = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
class Add :fengzhuang
{
public override double GetResult()
{
double result = 0;
result = A + B;
return result;
}
}
class Sub : fengzhuang
{
public override double GetResult()
{
double result = 0;
result = A - B;
return result;
}
}
class Mul : fengzhuang
{
public override double GetResult()
{
double result = 0;
result = A * B;
return result;
}
}
class Div :fengzhuang
{
public override double GetResult()
{
double result = 0;
if (B == 0)
throw new Exception("除数不能为0");
result = A / B;
return result;
}
}
public class Factory
{
public static fengzhuang Cal(string operate)
{
fengzhuang oper = null;
switch (operate)
{
case "+":
oper = new Add();
break;
case "-":
oper = new Sub();
break;
case "*":
oper = new Mul();
break;
case "/":
oper = new Div();
break;
}
return oper;
}
}
具体代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class index : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Cal_Click(object sender, EventArgs e)
{
Calculator oper;
string strOperate = DropDownList1.SelectedItem.ToString();
oper = Factory.Cal(strOperate);
oper.A = Convert.ToDouble(TextBox1.Text);
oper.B = Convert.ToDouble(TextBox2.Text);
string answer = Convert.ToString(oper.GetResult());
string result = TextBox1.Text + DropDownList1.SelectedItem.ToString() + TextBox2.Text;
if (TextBox3.Text == answer)
{
Response.Write("<script>alert(‘回答正确!‘)</script>");
ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim());
}
else
{
Response.Write("<script>alert(‘答题错误!‘)</script>");
ListBox1.Items.Add(result + "=" + TextBox3.Text.Trim() );
}
TextBox1.Text = "";
TextBox2.Text = "";
TextBox3.Text = "";
}
}