您好,登錄后才能下訂單哦!
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。