C#委托全写在一个窗体里还是委托么
double first, second;
string input;
bool sfcz = false;
delegate double ProcessDelegate(double param1,double param2);
private double add(double param1, double param2)
{
return param1 + param2;
}
private double del(double param1, double param2)
{
return param1 - param2;
}
private double Multiply(double param1, double param2)
{
return param1 * param2;
}
private double Divide(double param1, double param2)
{
return param1 / param2;
}
//数字1按钮事件 其他数字类似 不多写了
private void button1_Click(object sender, EventArgs e)
{
if (sfcz)
{
sfcz = false;
textBox1.Text = "";
}
textBox1.Text += "1";
}
//加号按钮事件 其他减乘除类似 不多写了
private void button11_Click(object sender, EventArgs e)
{
if (textBox1.Text.Trim() != "")
{
sfcz = true;
}
first = Convert.ToDouble(textBox1.Text);
input = "加";
}
//等号按钮事件
private void button15_Click(object sender, EventArgs e)
{
second = Convert.ToDouble(textBox1.Text);
ProcessDelegate process;
if (input == "加")
{
process = new ProcessDelegate(add);
}
else if (input == "减")
{
process = new ProcessDelegate(del);
}
else if (input == "乘")
{
process = new ProcessDelegate(Multiply);
}
else if (input == "除")
{
process = new ProcessDelegate(Divide);
}
else
{
//textBox1.Text = "请选择操作符";
MessageBox.Show("请选择操作符");
return;
}
textBox1.Text = process(first, second).ToString();
}
算,但是你这么做属于多此一举。为了演示委托的妙处,给你的代码修改下:
private void button15_Click(object sender, EventArgs e)
{
second = Convert.ToDouble(textBox1.Text);
Dictionary<string, ProcessDelegate> dict = new Dictionary<string, ProcessDelegate>();
dict.Add("加", new ProcessDelegate(add));
dict.Add("减", new ProcessDelegate(del));
dict.Add("乘", new ProcessDelegate(Multiply));
dict.Add("除", new ProcessDelegate(Divide));
if (!dict.HasKey(input))
{
//textBox1.Text = "请选择操作符";
MessageBox.Show("请选择操作符");
return;
}
textBox1.Text = dict[input](first, second).ToString();
}