委托是.NET引进的一种极其类似中介的类型,其执行的基本原理就是,首先需要一个
返回数据的类型,执行参数的类型,然后就可以把这个委托指定到某个函数来执行,当
外部执行的时候看到的是委托的执行,看不到函数的执行。
其使用的方法简言之:
1:声明一个委托
2:创建一个委托需真正要执行的函数
3:执行委托即间接执行真实的业务。
例一:
声明一个委托:public delegate void MyFirstDelegate(string sPut);
委托需要执行的中间层真实代码:
public void FirstVoidFunction(string sPut){
Console.WriteLine("Execute:FistVoidFunction({0})",sPut);
}
创建一个委托实例并执行
MyFirstDelegate ObjDele = new MyFirstDelegate(Obj.FirstVoidFunction);
ObjDele("参数");
执行的结果
Execute:FistVoidFunction(参数)
例二,执行一个具有返回值的委托:
public delegate int MySecondDelegate(int iPut);
public int SecondIntFunction(int sPut){
return sPut * sPut;
}
MySecondDelegate ObjDele2 = new MySecondDelegate(Obj.SecondIntFunction);
int rId=ObjDele2(9);
关于委托,基本上就是这么回事,和接口是非常类似的。
关于更多,查看Delegate类。
另外本文的小例子。
using System;
using System.Collections.Generic;
using System.Text;
class DemoMain{
public delegate void MyFirstDelegate(string sPut);
public delegate int MySecondDelegate(int iPut);
public static void Main(string[] args){
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("开始执行程序...");
Console.ForegroundColor = ConsoleColor.White;
DemoMain Obj =new DemoMain();
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("执行返回void的函数");
Console.ForegroundColor = ConsoleColor.White;
MyFirstDelegate ObjDele = new MyFirstDelegate(Obj.FirstVoidFunction);
ObjDele("参数");
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("执行返回Int的函数");
Console.ForegroundColor = ConsoleColor.White;
MySecondDelegate ObjDele2 = new MySecondDelegate(Obj.SecondIntFunction);
Console.WriteLine("Execute:SecondIntFunction({0})={1}",9,ObjDele2(9));
//Console.ReadLine();
}
public void FirstVoidFunction(string sPut){
Console.WriteLine("Execute:FistVoidFunction({0})",sPut);
}
public int SecondIntFunction(int sPut){
return sPut * sPut;
}
}
天气:大雨,ccdot发表于2008-4-25 16:37:37,阅读了148次,共有个0回复.