.Net委托应用(二)
委托数组的运用,如下例:
class program
{
delegate double DoubleOp(double x);
static double multi(double value)
{
return value*2;
}
static double square(double value)
{
return value*value;
}
static void ProcessAndDisplay(DoubleOp action,double value)
{
double result=action(value);
Console.WriteLine("Value is {0},result of operation is {1}",value,result);
}
static void Main()
{
DoubleOp[] operations={new DoubleOp(multi),new DoubleOp(square)};
for(int index=0;index<operations.Length;index++)
{
ProcessAndDisplay(operations,2.0);
ProcessAndDisplay(operations,29.05);
ProcessAndDisplay(operations,28.08);
Console.WriteLine();
}
}
}
多播委托,委托也可以包含多个方法,这种委托称为多播委托.如果调用多播委托,就可以按顺序连续调用多个方法.为此,委托的签名就必须返回void,实际上,编译器发现某个委托返回void,就会自动假定这是一个多播委托.示例如下:
DoubleOp operation1=new DoubleOp(multi);
DoubleOp operation2=new DoubleOp(square);
DoubleOp operation3=operation1+operation2;
多播委托还识别运算符-和-=,以从委托中删除方法调用.
多播委托是一个派生于System.MulticastDelegate的类,System.MulticastDelegate又派生于基类
System.Delegate. System.MulticastDelegate其他成员允许把多个方法调用链接在一起,成为一个列表.
如果使用多播委托,就应注意到同一个委托调用方法链的顺序并未正式定义.因此应避免编写依赖于以任意特定顺序调用方法的代码.
委托在线程中的运用:
众所周知,线程是不安全的,在线程中执行程序,需要给他提供一个安全的处理方式.于是就用到了委托.
先声明一个委托方法类:
private delegate void ShowOnServerStatus(string str);
处理的代码(要被委托的方法):
private void ShowOnServer(string str)
{
textbox3.AppendText(str+"\r\n");
}
启动一个线程:
Thread thre = new Thread(new ThreadStart(accp));
thre.Start();
线程要处理的方法accp():
private void accp()
{
if (textBox3.InvokeRequired) //为了线程中的安全.
{
//定义委托方法对象d,並指派showOnserver给这个委托的方法.
ShowOnServerStatus d = new ShowOnServerStatus(showOnserver);
this.Invoke(d, "主机开始监听....\r\n");
//执行这个委托的方法.
}
}