笔记来自金旭亮的电子教案“委托与事件”中的委托部分和他的书《.NET4.0面向对象编程漫谈 基础篇》
委托是.NET中事件、异步调用和多线程开发的技术基础
委托可以看成是方法的容器(最典型的是控件事件中的+=和-=符号),将某种具体的方法装入后,可以把它当成方法一样调用。
C#编译器对委托的处理方法:
public delegate int MathOptDelegate(int val1,int val2);
public class MathOptDelegate:System.MulticastDelegate
{
public MathOptDelegate(Object target,Int32 methodPtr);
public void virtual Invoke(Int32 val1,Int32 val2);
public virtual IAsyncResult BeginInvoke(
Int32 val1,Int32 val2,ASyncCallback,Object object);
public virtual void EndInvoke(IAsyncResult result);
}
public class MathOpt
{
public int Add(int arg1,int arg2)
{
return arg1+arg2;
}
}
public delegate int MathOptDelegate(int val1,int val2);
void MainFormLoad(object sender, EventArgs e)
{
MathOptDelegate oppDel;
MathOpt obj=new MathOpt();
oppDel=obj.Add;
string str=oppDel(20,12).ToString();
MessageBox.Show(string.Format("20+12={0}",str),"Delegate Demo", MessageBoxButtons.OK);
}
public delegate double CalculateDelegate(double x,double y);
public delegate double CalculateDelegate(double x,double y);
private CalculateDelegate curOpt;
void DoCalculate(CalculateDelegate calMethod)
{
double x,y;
x=int.Parse(textBox1.Text);y=int.Parse(textBox2.Text);
labResult.Text=string.Format("结果:{0}",calMethod(x,y));
}
double Add(double x,double y){return x+y;}
double Subtract(double x,double y){return x-y;}
double Multiplicate(double x,double y){return x*y;}
double Divide(double x,double y){return x/y;}
void RadioButton1CheckedChanged(object sender, EventArgs e)
{
foreach(RadioButton r in groupBox2.Controls)
{
if(r is RadioButton)
{
if(r.Checked==true)
{
int i=groupBox2.Controls.IndexOf(r);
switch(i)
{
case 0:
curOpt=Add;
break;
case 1:
curOpt=Subtract;
break;
case 2:
curOpt=Multiplicate;
break;
case 3:
curOpt=Divide;
break;
}
}
}
}
DoCalculate(curOpt);
}
public delegate void ShowInfoDelegate(string info);
void MainFormLoad(object sender,EventArgs e)
{
ChildForm c=new ChildForm();
c.recorder=Record;
c.Show();
}
private void Record(string str)
{
label1.Text=str;
}
public ShowInfoDelegate recorder;
private int counter;
void Button1Click(object sender, EventArgs e)
{
counter++;
if(recorder!=null)
recorder(counter.ToString());
}