using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Add(int num1, int num2) { Console.Write(num1 + num2); Console.Write(' '); } static void Subs(int i, int j) { Console.Write(i - j); Console.Write(' '); } delegate void Calc(int i,int j);//定义一个代理类型Calc,它可以用于定义各种参数为两个整数的任意方法;故 static void Main(string[] args) { //Calc c1=new Calc(Add); //Calc c2=new Calc(Subs); //c1(3, 4); //c2(3, 4); Calc c = Add; c += Subs; c(8888, 7); Console.ReadKey(); } } }
the second example:
using System; using System.Collections.Generic; using System.Text; namespace Delegate { //定义委托,它定义了可以代表的方法的类型 public delegate void GreetingDelegate(string name); class Program { public class GreetingManager { //在GreetingManager类的内部声明delegate1变量 public GreetingDelegate delegate1; public void GreetPeople(string name) { if(delegate1!=null) this.delegate1(name); } } private static void EnglishGreeting(string name) { Console.WriteLine("Morning, " + name); } private static void ChineseGreeting(string name) { Console.WriteLine("早上好, " + name); } private static void JapaneseGreeting(string name) { Console.WriteLine("おはよう, " + name); } //注意此方法,它接受一个GreetingDelegate类型的方法作为参数 static void Main(string[] args) { GreetingManager gm = new GreetingManager(); gm.delegate1 = EnglishGreeting; gm.delegate1 += ChineseGreeting; gm.delegate1 += JapaneseGreeting; gm.GreetPeople("Jimmy Zhang"); Console.ReadKey(); } } }