项目实战:计算器#
来源:
D:\study\C#1\WinForm\0804-作业\0804-作业\FrmMain.cs
用 TextBox 显示算式,用多个数字按钮共用一个事件(sender 区分)实现输入,支持四则运算、退格、清空。
1. 整体思路#
界面:TextBox(显示屏) + 数字按钮(0-9) + 运算符按钮(+ - × ÷) + 功能按钮(= 退格 清空)
核心技巧:数字按钮共用一个 num 事件,通过 sender 拿到按钮上的数字
2. 数字输入(sender 共用事件)#
private void num(object sender, EventArgs e)
{
if (textBox1.Text == "0")
{
// 首位数:直接替换 "0"
textBox1.Text = (sender as Button)?.Text;
}
else
{
// 后续数字:追加
textBox1.Text += (sender as Button)?.Text;
}
}
💡 10 个数字按钮全部绑定到
num事件,(sender as Button)?.Text拿到点击的那个数字。?.是空值条件运算符:sender 不是 Button 时返回 null 而不报错。
3. 运算符处理(等号时计算)#
private void symbol(object sender, EventArgs e)
{
Equal(sender, e); // 先计算已有算式
textBox1.Text += (sender as Button)?.Text; // 再追加运算符
}
4. 四则运算(String.Split 解析)#
private void Equal(object sender, EventArgs e)
{
string text = textBox1.Text;
if (text.Contains("+"))
{
textBox1.Text = (double.Parse(text.Split('+')[0]) + double.Parse(text.Split('+')[1])).ToString();
}
else if (text.Contains("-"))
{
textBox1.Text = (double.Parse(text.Split('-')[0]) - double.Parse(text.Split('-')[1])).ToString();
}
else if (text.Contains("×"))
{
textBox1.Text = (double.Parse(text.Split('×')[0]) * double.Parse(text.Split('×')[1])).ToString();
}
else if (text.Contains("÷"))
{
// 除数为 0 的校验
if (double.Parse(text.Split('÷')[1]) != 0)
{
textBox1.Text = (double.Parse(text.Split('÷')[0]) / double.Parse(text.Split('÷')[1])).ToString();
}
else
{
MessageBox.Show("非法数据!");
textBox1.Text = null;
}
}
}
💡 解析思路:
"12+34".Split('+')→["12", "34"],取下标 0、1 转成 double 运算。这是字符串处理的经典用法。
5. 退格与清空#
// 清空
private void button12_Click(object sender, EventArgs e)
{
textBox1.Text = "0";
}
// 退格(删除最后一个字符)
private void button17_Click(object sender, EventArgs e)
{
if (textBox1.Text.Length > 0)
{
textBox1.Text = textBox1.Text.Remove(textBox1.Text.Length - 1, 1);
}
if (textBox1.Text.Length == 0)
{
textBox1.Text = "0";
}
}
💡
string.Remove(起始位置, 个数)删除指定位置的字符;Length - 1就是最后一个字符的位置。
6. 关闭确认#
private void Fr_FormClosing(object sender, FormClosingEventArgs e)
{
DialogResult dialogResult =
MessageBox.Show("是否关闭", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1);
if (dialogResult == DialogResult.Cancel)
{
e.Cancel = true; // 点取消不关闭
}
}
7. 知识点回顾#
| 技术点 | 用法 |
|---|---|
| sender 共用事件 | 数字按钮 → (sender as Button)?.Text |
| 字符串拆分 | Split('+') 解析算式 |
| 类型转换 | double.Parse() 字符串转数字 |
| 异常防护 | 除数为 0 提示「非法数据」 |
| 字符串删除 | Remove(Length-1, 1) 退格 |
| 关闭确认 | FormClosing + e.Cancel |
💡 改进方向(扩展练习):支持连续运算(如
1+2+3)、支持小数、支持键盘输入数字、负数处理。源码FrmMain.cs中a、b两个 double 字段可配合运算符暂存实现更完整的计算逻辑。
相关笔记#
- 事件的联动响应与 sender — sender 共用事件
- 事件的基本使用 — 事件基础