1. 程式人生 > >C#委托與回調的應用體會(一)

C#委托與回調的應用體會(一)

n) ace ted initial 計算 con textbox click ble

在實現定積分通用函數計算程序設計過程中,第一次使用C#的委托特性,個人感覺C#的委托有點類似指針,就是把一個方法做成地址傳遞過去。盡管這種理解不一定嚴謹,但是取得的效果確實差不多。

以下便是委托的實際應用~

namespace functionTheOne
{
public partial class Form1 : Form
{
private delegate double Function(double x);
private Function function;
public Form1()
{
InitializeComponent();
}

private void label1_Click(object sender, EventArgs e)
{

}

private void button1_Click(object sender, EventArgs e)
{
if (radioButton3.Checked == true)
{
double a; double b; double z;
a = Convert.ToDouble(textBox1.Text);
b = Convert.ToDouble(textBox2.Text);
function = new Function(jishuan1);
hanshu(a, b, function);
}
if (radioButton2.Checked == true)
{
double a; double b; double z;
a = Convert.ToDouble(textBox1.Text);
b = Convert.ToDouble(textBox2.Text);
function = new Function(jishuan2);
hanshu(a, b, function);
}
}

private void checkBox1_CheckedChanged(object sender, EventArgs e)
{

}

private void label3_Click(object sender, EventArgs e)
{

}

private void Form1_Load(object sender, EventArgs e)
{

}

private void listView1_SelectedIndexChanged(object sender, EventArgs e)
{

}

private void radioButton2_CheckedChanged(object sender, EventArgs e)
{

}
private double hanshu(double a,double b,Function ch)//計算通用的函數
{
double sum=0;
for(int i = 0; i < 10000; i++)
{
sum = sum + (a-b)/10000*(ch(((a - b) / 10000 )*i+b)); //a是上限,b是下限
}
textBox3.Text = Convert.ToString(sum);
return sum;
}
private double jishuan1(double x )
{
return x;
}
private double jishuan2(double x)
{
return x * x;
}
}

}

C#委托與回調的應用體會(一)