在ASP.NET里实现计算器代码的封装
一、具体代码
Default2.aspx.cs
public partial class Chapter1_Default2 : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } int a = 0; private int t; public static int Count=0; public static int right=0; protected void Button1_Click(object sender, EventArgs e) { int a = int.Parse(TextBox1.Text.Trim()); int b = int.Parse(TextBox3.Text.Trim()); Char c = Convert.ToChar(TextBox2.Text.Trim()); Lei con = new Lei(); con.Max(a, b, c); if (con.Answer == int.Parse(TextBox4.Text.Trim())) { Label1.Text=("恭喜你,小朋友!回答正确!"); Label1.ForeColor=Color.Blue; right++; } else { Label1.Text = ("回答错误,继续加油!小朋友"); Label1.ForeColor = Color.Red; } } protected void Button2_Click(object sender, EventArgs e) { Count++; StreamWriter baocun1 = File.AppendText("C:\\baocun1.txt"); baocun1.WriteLine(TextBox1.Text); baocun1.Close(); StreamWriter baocun2 = File.AppendText("C:\\baocun2.txt"); baocun2.WriteLine(TextBox2.Text); baocun2.Close(); StreamWriter baocun3 = File.AppendText("C:\\baocun3.txt"); baocun3.WriteLine(TextBox3.Text); baocun3.Close(); ListBox1.Items.Add(TextBox1.Text + TextBox2.Text + TextBox3.Text + "="); TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; } protected void Button3_Click(object sender, EventArgs e) { TextBox1.BackColor = Color.Yellow; TextBox2.BackColor = Color.Yellow; TextBox3.BackColor = Color.Yellow; TextBox4.BackColor = Color.Yellow; TextBox1.Enabled = false; TextBox2.Enabled = false; TextBox3.Enabled = false; string[] m = new string[100]; m = File.ReadAllLines("C:\\baocun1.txt"); TextBox1.Text = m[a]; string[] n = new string[100]; n = File.ReadAllLines("C:\\baocun2.txt"); TextBox2.Text = n[a]; string[] v = new string[100]; v = File.ReadAllLines("C:\\baocun3.txt"); TextBox3.Text = v[a]; a++; } protected void Button4_Click(object sender, EventArgs e) { TextBox1.Text = ""; TextBox2.Text = ""; TextBox3.Text = ""; TextBox4.Text = ""; Label1.Text = ""; } protected void Button5_Click(object sender, EventArgs e) { Label6.Text = "总计"; Label7.Text = "正确"; Label8.Text = "正确率"; Label3.Text = Count.ToString(); Label4.Text = right.ToString(); Label5.Text = ((right / (double)(Count)) * 100).ToString() + "%"; } }
封装代码:
类代码要写在App_Code里
public class Lei { public int Sum; public int Answer { get { return Sum; } } public int Max(int n1,int n2,char yunsuanfu) { if (yunsuanfu == '+') { return Sum = n1 + n2; } else if (yunsuanfu == '-') { return Sum = n1 - n2; } else if (yunsuanfu == '/') { return Sum = n1 / n2; } else if (yunsuanfu == '*') { return Sum = n1 * n2; } return Sum; } }
二、测试