class Program { static void HandleDemoEvent(object sender, EventArgs e) { Console.WriteLine("Handled by HandleDemoEvent"); } static void Main(string[] args) { Console.WriteLine("c#1 委托示例"); Person jon = new Person("Jon"); Person tom = new Person("Tom"); StringProcessor josVoice, tomsVoice, background; //创建3个委托实例 josVoice = new StringProcessor(jon.Say); tomsVoice = new StringProcessor(tom.Say); background = new StringProcessor(Background.Note); josVoice("Hello,Lichuan"); tomsVoice.Invoke("Hello,Doddy!"); background("An airplane flies past."); Console.WriteLine("c#2 委托示例"); EventHandler handler; handler = new EventHandler(HandleDemoEvent);//指定委托类型和方法 handler(null, EventArgs.Empty); handler = HandleDemoEvent;//隐式转换成委托实例 handler(null, EventArgs.Empty); handler = delegate(object sender, EventArgs e)//用一个匿名方法来指定操作 { Console.WriteLine("Handled anonymously"); }; handler(null, EventArgs.Empty); handler = delegate //使用匿名方法的简写 { Console.WriteLine("Handled anonymously again"); }; handler(null, EventArgs.Empty); Console.ReadKey(); } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SRLJCSHAP.委托.Demo { delegate void StringProcessor(string input);//声明委托类型 public class Person { string name; public Person(string Name) { this.name = Name; } //声明兼容的实例方法 public void Say(string Msg) { Console.WriteLine("{0} says: {1}", name, Msg); } } public class Background { //声明兼容的静态方法 public static void Note(string note) { Console.WriteLine("({0})", note); } } }