using system;
using system.collections.generic;
using system.linq;
using system.text;
using system.threading.tasks;namespace csharp控制台练习{class program{//【1】、声明委托 (定义一个函数的原形:返回值 参数类型和个数)public delegate int demodelegate(int a, int b);//【2】、要存放的方法等具体实现功能(比如加减法)static int add(int a, int b) { return a b; }static int sub(int a, int b) { return a - b; }static void main(string[] args){//【3】、定义委托变量,并且关联要存放于该变量的方法demodelegate objdel = new demodelegate(add);//【4】、通过委托调用方法,而不是直接调用方法console.writeline( objdel(10, 20));objdel -= add;objdel = sub;console.writeline( objdel(10, 20));console.readkey();}}
}
此程序输出结果为30 -10.
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;namespace csharp窗体练习
{public partial class frmother1 : form{public frmother1(){initializecomponent();}public void receive(string counter){labcounter.text = counter;}}
}
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.threading.tasks;
using system.windows.forms;namespace csharp窗体练习
{public delegate void showcounterdele(string counter);//【1】声明个委托,一般在类外面声明public partial class form1 : form{showcounterdele showcounterdel; //【2】定义委托对象public form1(){initializecomponent();frmother frmother = new frmother();frmother1 frmother1 = new frmother1();frmother2 frmother2 = new frmother2();showcounterdel = frmother.receive; //【3】将委托对象与方法关联起来showcounterdel = frmother1.receive;showcounterdel = frmother2.receive;frmother.show();frmother1.show();frmother2.show();}private int count = 0;private void btncounter_click(object sender, eventargs e){count ;showcounterdel(count.tostring()); //【4】、通过委托调用方法}private void btnclear_click(object sender, eventargs e){count=0;showcounterdel(count.tostring());}}
}
执行上面程序,点击主窗体中的按钮,从窗体会显示单击次数。点击主窗体的复位按钮然后计数归零。