using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 委托及事件 { class Program { static void Main(string[] args) { Emplyee em = new Emplyee(); Reporter re = new Reporter(); //指明事件触发后,由谁来处理 em.PlayGame+=new DelegateClassHandle(re.Notify); em.Game(); Console.ReadKey(); } } public delegate void DelegateClassHandle(); //定义托管 public class Emplyee //定义员工类 { public event DelegateClassHandle PlayGame; //定义托管的绑定事件PlayGame public void Game() //定义一个Game方法 { if (PlayGame != null) //判断事件是否为空 { Console.WriteLine("哈哈,开始玩游戏"); PlayGame(); } } } public class Reporter //定义一个报告类 { public void Notify() { Console.WriteLine("报告老板,有人玩游戏"); } }
带参数的委托:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 委托及事件 { class Program { static void Main(string[] args) { Employee el = new Employee("二逼青年",888); Reporter re = new Reporter(); //指明事件触发后,由谁来处理 el.PlayGame+=new DelegateClassHandle(re.Notify); el.Game(); Console.ReadKey(); } } /// <summary> /// /// </summary> /// <param name="sen">触发事件的源</param> /// <param name="e">同时携带的参数</param> public delegate void DelegateClassHandle(object sen, cc e); //定义托管 public class Employee //定义员工类 { string _name; int _number; public string Name { get { return _name; } set { _name = value; } } public int Number { get { return _number; } set { _number = value; } } public event DelegateClassHandle PlayGame; //定义托管的绑定事件PlayGame public Employee(string nm, int nu) { _name = nm; _number = nu; } public void Game() //定义一个Game方法 { if (PlayGame != null) //判断事件是否为空 { Console.WriteLine("哈哈,开始玩游戏"); //实例化一个参数类 cc e = new cc(); e.Name = _name; e.Number = _number; PlayGame(this,e); } } } public class Reporter //定义一个报告类 { public void Notify(object sen, cc e) { Console.WriteLine("报告老板,{0}在{1}玩游戏",e.Name,e.Number ); } } public class cc : EventArgs { public string Name = ""; public int Number = 0; } }
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。