SlideShare a Scribd company logo
1 of 52
Delegate & Event 1 20/03/2011
Table of Contents ,[object Object]
Definition of delegate
Working with delegates in C#
Multicast delegate
Problem & Solution for generic Sort method
Event
What is event
Event & delegate
Publishing & subscribing
Demo using event
Summary2 16/01/2011
Definition of delegate ,[object Object]
Using in event-handling model of C#
Like C/C++ method pointers, but more specific
Type safe
Object- oriented mechanism
Delegates are classes
Can create instances of delegates
Delegates can refer one or more methods3 16/01/2011
Definition of delegate ,[object Object]
Return type
Sequence of parameter types
Any method has same signature can add to instance of delegate
Delegate instances have the list of method references
Using “+=” for adding method to instance
Using “-=” for removing method out of instance4 16/01/2011
Working with delegates Define a delegate in namespace or class 5 16/01/2011 public delegate void MyDelegate1(int x, int y);  Delegate for methods:  void  ABC( int, int ) public delegate string MyDelegate2(float f);  Delegate for methods: string XYZ( float )
Working with delegates Instance of delegate 6 16/01/2011 public delegate void MyDelegate1(int  x, int y);  class Test { public void Method1(int a, int b) {        // body of method } … } Test t = new Test(); MyDelegate1 d1 = new MyDelegate1( t.Method1 );
Working with delegate Instance of delegate 7 16/01/2011 public delegate string MyDelegate2(float f);  class Test { … public static string Method2(float f) {        // body of method } } MyDelegate2 d2 = new MyDelegate2( Test.Method2 );
Working with delegate Invoking delegates 8 16/01/2011 d1 int x = 5, y = 10; d1(x, y); d1(10, 20); int y = 2; d1(100, y); d2 float f =0.5f; string s = d2(f); string s = d2(100);
Invoking multiple delegate Using only for delegates with no return value 9 16/01/2011 No return class Test     {         public delegate voidMyDelegate3(int n1, int n2);         static void Print(int x, int y)         { Console.WriteLine("x={0}, y={1}", x, y);         }         static void Sum(int a, int b)         { Console.WriteLine("Tong={0}", a + b);         }	          // (cont)… }
Invoking multiple delegate 10 16/01/2011 class  Test {         //…         static void Main(string[] args)         {             MyDelegate3 md = new MyDelegate3(Print); md+= new MyDelegate3(Sum); md(5, 10); md -= new MyDelegate3(Print); md(50, 60);         } } x=5, y=10 Tong=15 Tong=110
11 16/01/2011 Demo 1
Problem 12 16/01/2011 How to build the Sort method for array of objects of any data type? Sort method
Problem Survey The objects are (primitive) data type such as: long, int, float, string…so easy to do! In other case, object is complex data type, how to do? 13 16/01/2011 Which criteria for  comparing?
Solution Objects have to define their order (Compare) Using delegate to pass “compare method” into Sort method. 14 16/01/2011 void Sort(object[] list, CompareObjcmp) This delegate refers to Compare method of class which need to sort.
Solution Define delegate CompareObj for Sort method 15 16/01/2011 Name of delegate type public delegate intCompareObj(object o1, object o2) -1  :     o1 “<“ o2  0  :     o1 “=“ o2  1  :     o1 “>” o2 Two objects passed
Solution 16 16/01/2011 Delegate will refer to compare method of class Definition of Sort method public static void Sort(object[] objs, CompareObj cmp) {         for(int i=0; i < objs.Length-1;i++)             for(int j=objs.Length-1; j>i;j--)                 if (cmp(objs[j],objs[j-1]) == -1) 	Swap( objs[j], objs[j-1] ); } Invoking delegate (refer Compare method of class)
Solution Class support Sort method required Provide a Compare method (or more) Method signature is same with the delegate 17 16/01/2011 class Person{     private string 	name;     private int 	weight;     private int 	yearOfBirth; public static  int CompareName(object p1, object p2)     {             return  string.Compare(((Person)p1).name, ((Person)p2).name);     } }
Solution 18 16/01/2011         //…         Person[] persons= new Person[4];         persons[0] = new Person(“QuyMui",20,2004);         persons[1] = new Person(“Ha Giang",62,1978);         persons[2] = new Person(“Ngoc Thao",47, 1979);         persons[3] = new Person(“Ha Nam",4,2009); // create instance of delegate refer to Person.CompareName         CompareObjcmp = new CompareObj(Person.CompareName); HaGLib.Sort(persons,cmp); Class contains static Sort method
19 16/01/2011 Demo 2
20 16/01/2011 Event
Event Cơ chế thông điệp giữa các lớp hay các đối tượng Có thể thông báo cho lớp khác biết được khi một lớp có phát sinh điều gì đó Publisher: lớp phát sinh sự kiện Subscriber: lớp nhận hay xử lý khi sự kiện xảy ra 21 16/01/2011
Event Trong môi trường giao diện GUIs (Graphical User Interfaces: GUIs): Button đưa ra sự kiện “Click”, cho phép lớp khác có thể đáp ứng (xử lý) khi sự kiện này xảy ra. VD: Button “Add” trong Form, khi sự kiện click xảy ra thì Form thực hiện lấy dữ liệu từ các TextBox đưa vào ListBox… 22 16/01/2011
Event Một lớp publish tập các event cho phép các lớp khác subscribe Button là lớp publish đưa ra event: click  Form là lớp subscribe có phần xử lý riêng khi “click” của Button kích hoạt. 23 16/01/2011 event subscribe Thông báo publish B A Đăng ký C
Event & Delegate Sự kiện trong C# được thực thi nhờ uỷ thác Lớp publishing định nghĩa ủy thác Những lớp subscribing phải thực thi Khi sự kiện xuất hiện thì phương thức của lớp subscribing được gọi thông qua uỷ thác. Phương thức để xử lý sự kiện gọi là trình xử lý sự kiện (event handler) 24 16/01/2011
Event & Delegate ,[object Object]
Trảvềgiátrị void
Thamsố 1:  nguồnphátsinhsựkiện, đâychínhlàđốitượng publisher
Thamsố 2: làđốitượngthuộclớpdẫnxuấttừEventArgs
Phảithựchiệntrìnhxửlýsựkiệntheođúngmẫutrên!25 16/01/2011

More Related Content

What's hot

Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingPhuoc Nguyen
 
Oop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnOop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnTráng Hà Viết
 
Hdth07 ltudql02-linq-ep1
Hdth07 ltudql02-linq-ep1Hdth07 ltudql02-linq-ep1
Hdth07 ltudql02-linq-ep1Dũng Đinh
 
02 chuong 2 - lay du lieu theo cach connected
02   chuong 2 - lay du lieu theo cach connected02   chuong 2 - lay du lieu theo cach connected
02 chuong 2 - lay du lieu theo cach connectedtruong le hung
 
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02
02 chuong2-laydulieutheocachconnected-140404114611-phpapp0202 chuong2-laydulieutheocachconnected-140404114611-phpapp02
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02huynhtrong774129
 
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )Đông Lương
 

What's hot (10)

Android Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML ParsingAndroid Nâng cao-Bài 8-JSON & XML Parsing
Android Nâng cao-Bài 8-JSON & XML Parsing
 
Bai05 ket tapvakethua
Bai05 ket tapvakethuaBai05 ket tapvakethua
Bai05 ket tapvakethua
 
Bai07 da hinh
Bai07 da hinhBai07 da hinh
Bai07 da hinh
 
Oop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiệnOop unit 12 đồ họa và xử lý sự kiện
Oop unit 12 đồ họa và xử lý sự kiện
 
Hdth07 ltudql02-linq-ep1
Hdth07 ltudql02-linq-ep1Hdth07 ltudql02-linq-ep1
Hdth07 ltudql02-linq-ep1
 
Bai08 lap trinhtongquat
Bai08 lap trinhtongquatBai08 lap trinhtongquat
Bai08 lap trinhtongquat
 
Chuong 4
Chuong 4Chuong 4
Chuong 4
 
02 chuong 2 - lay du lieu theo cach connected
02   chuong 2 - lay du lieu theo cach connected02   chuong 2 - lay du lieu theo cach connected
02 chuong 2 - lay du lieu theo cach connected
 
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02
02 chuong2-laydulieutheocachconnected-140404114611-phpapp0202 chuong2-laydulieutheocachconnected-140404114611-phpapp02
02 chuong2-laydulieutheocachconnected-140404114611-phpapp02
 
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
Lập Trình Hướng Đối Tượng trong Java ( Vietnamese )
 

Similar to P05 delegate & event 2009

W3 p5 delegate & eventb
W3 p5   delegate & eventbW3 p5   delegate & eventb
W3 p5 delegate & eventbTuấn Huỳnh
 
OOP_01_Tong Quan LTHDT.pdf
OOP_01_Tong Quan LTHDT.pdfOOP_01_Tong Quan LTHDT.pdf
OOP_01_Tong Quan LTHDT.pdfssuserd01a5c
 
Chiêu thức lập trình
Chiêu thức lập trìnhChiêu thức lập trình
Chiêu thức lập trìnhlongkenj
 
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...MasterCode.vn
 
01 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_101 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_1htpsccbb159
 
Bài 7: Toast – Dialog, ListView & Binding
Bài 7: Toast – Dialog, ListView & BindingBài 7: Toast – Dialog, ListView & Binding
Bài 7: Toast – Dialog, ListView & Bindinghoccungdoanhnghiep
 
Chuan viet code va thiet ke giao dien trong C#
Chuan viet code va thiet ke giao dien trong C#Chuan viet code va thiet ke giao dien trong C#
Chuan viet code va thiet ke giao dien trong C#Kuli An
 
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTBài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTMasterCode.vn
 
Lập trình Android cơ bản bằng tiếng Việt
Lập trình Android cơ bản bằng tiếng ViệtLập trình Android cơ bản bằng tiếng Việt
Lập trình Android cơ bản bằng tiếng Việtlaptrinhandroid
 
Meo lap trinh_tech24.vn
Meo lap trinh_tech24.vnMeo lap trinh_tech24.vn
Meo lap trinh_tech24.vnphiagame
 
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPT
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPTBÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPT
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPTMasterCode.vn
 
Session 08 Final
Session 08 FinalSession 08 Final
Session 08 FinalSamQuiDaiBo
 
Auto it (upload_by_nguyentin2703)
Auto it (upload_by_nguyentin2703)Auto it (upload_by_nguyentin2703)
Auto it (upload_by_nguyentin2703)Rain Bi
 
Bài giảng kỹ thuật lập trình hook
Bài giảng kỹ thuật lập trình hookBài giảng kỹ thuật lập trình hook
Bài giảng kỹ thuật lập trình hookjackjohn45
 
Android report
Android reportAndroid report
Android reportMinh Đệ
 

Similar to P05 delegate & event 2009 (20)

W3 p5 delegate & eventb
W3 p5   delegate & eventbW3 p5   delegate & eventb
W3 p5 delegate & eventb
 
User Control
User ControlUser Control
User Control
 
OOP_01_Tong Quan LTHDT.pdf
OOP_01_Tong Quan LTHDT.pdfOOP_01_Tong Quan LTHDT.pdf
OOP_01_Tong Quan LTHDT.pdf
 
Chiêu thức lập trình
Chiêu thức lập trìnhChiêu thức lập trình
Chiêu thức lập trình
 
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
Bài 3: Lập trình giao diện điều khiển & Xử lý sự kiện - Lập trình winform - G...
 
Java Tieng Viet
Java Tieng VietJava Tieng Viet
Java Tieng Viet
 
01 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_101 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_1
 
01 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_101 ngon ngu_c#_phan_1
01 ngon ngu_c#_phan_1
 
Window Form
Window FormWindow Form
Window Form
 
Bài 7: Toast – Dialog, ListView & Binding
Bài 7: Toast – Dialog, ListView & BindingBài 7: Toast – Dialog, ListView & Binding
Bài 7: Toast – Dialog, ListView & Binding
 
Chuan viet code va thiet ke giao dien trong C#
Chuan viet code va thiet ke giao dien trong C#Chuan viet code va thiet ke giao dien trong C#
Chuan viet code va thiet ke giao dien trong C#
 
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPTBài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
Bài 2: Lập trình hướng đối tượng (OOP) - Giáo trình FPT
 
Lập trình Android cơ bản bằng tiếng Việt
Lập trình Android cơ bản bằng tiếng ViệtLập trình Android cơ bản bằng tiếng Việt
Lập trình Android cơ bản bằng tiếng Việt
 
Vb6 16 (9)
Vb6 16 (9)Vb6 16 (9)
Vb6 16 (9)
 
Meo lap trinh_tech24.vn
Meo lap trinh_tech24.vnMeo lap trinh_tech24.vn
Meo lap trinh_tech24.vn
 
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPT
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPTBÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPT
BÀI 6: Thủ tục (SUB) và hàm (FUNCTION) - Giáo trình FPT
 
Session 08 Final
Session 08 FinalSession 08 Final
Session 08 Final
 
Auto it (upload_by_nguyentin2703)
Auto it (upload_by_nguyentin2703)Auto it (upload_by_nguyentin2703)
Auto it (upload_by_nguyentin2703)
 
Bài giảng kỹ thuật lập trình hook
Bài giảng kỹ thuật lập trình hookBài giảng kỹ thuật lập trình hook
Bài giảng kỹ thuật lập trình hook
 
Android report
Android reportAndroid report
Android report
 

P05 delegate & event 2009

  • 1. Delegate & Event 1 20/03/2011
  • 2.
  • 6. Problem & Solution for generic Sort method
  • 13.
  • 15. Like C/C++ method pointers, but more specific
  • 19. Can create instances of delegates
  • 20. Delegates can refer one or more methods3 16/01/2011
  • 21.
  • 24. Any method has same signature can add to instance of delegate
  • 25. Delegate instances have the list of method references
  • 26. Using “+=” for adding method to instance
  • 27. Using “-=” for removing method out of instance4 16/01/2011
  • 28. Working with delegates Define a delegate in namespace or class 5 16/01/2011 public delegate void MyDelegate1(int x, int y); Delegate for methods: void ABC( int, int ) public delegate string MyDelegate2(float f); Delegate for methods: string XYZ( float )
  • 29. Working with delegates Instance of delegate 6 16/01/2011 public delegate void MyDelegate1(int x, int y); class Test { public void Method1(int a, int b) { // body of method } … } Test t = new Test(); MyDelegate1 d1 = new MyDelegate1( t.Method1 );
  • 30. Working with delegate Instance of delegate 7 16/01/2011 public delegate string MyDelegate2(float f); class Test { … public static string Method2(float f) { // body of method } } MyDelegate2 d2 = new MyDelegate2( Test.Method2 );
  • 31. Working with delegate Invoking delegates 8 16/01/2011 d1 int x = 5, y = 10; d1(x, y); d1(10, 20); int y = 2; d1(100, y); d2 float f =0.5f; string s = d2(f); string s = d2(100);
  • 32. Invoking multiple delegate Using only for delegates with no return value 9 16/01/2011 No return class Test { public delegate voidMyDelegate3(int n1, int n2); static void Print(int x, int y) { Console.WriteLine("x={0}, y={1}", x, y); } static void Sum(int a, int b) { Console.WriteLine("Tong={0}", a + b); } // (cont)… }
  • 33. Invoking multiple delegate 10 16/01/2011 class Test { //… static void Main(string[] args) { MyDelegate3 md = new MyDelegate3(Print); md+= new MyDelegate3(Sum); md(5, 10); md -= new MyDelegate3(Print); md(50, 60); } } x=5, y=10 Tong=15 Tong=110
  • 35. Problem 12 16/01/2011 How to build the Sort method for array of objects of any data type? Sort method
  • 36. Problem Survey The objects are (primitive) data type such as: long, int, float, string…so easy to do! In other case, object is complex data type, how to do? 13 16/01/2011 Which criteria for comparing?
  • 37. Solution Objects have to define their order (Compare) Using delegate to pass “compare method” into Sort method. 14 16/01/2011 void Sort(object[] list, CompareObjcmp) This delegate refers to Compare method of class which need to sort.
  • 38. Solution Define delegate CompareObj for Sort method 15 16/01/2011 Name of delegate type public delegate intCompareObj(object o1, object o2) -1 : o1 “<“ o2 0 : o1 “=“ o2 1 : o1 “>” o2 Two objects passed
  • 39. Solution 16 16/01/2011 Delegate will refer to compare method of class Definition of Sort method public static void Sort(object[] objs, CompareObj cmp) { for(int i=0; i < objs.Length-1;i++) for(int j=objs.Length-1; j>i;j--) if (cmp(objs[j],objs[j-1]) == -1) Swap( objs[j], objs[j-1] ); } Invoking delegate (refer Compare method of class)
  • 40. Solution Class support Sort method required Provide a Compare method (or more) Method signature is same with the delegate 17 16/01/2011 class Person{ private string name; private int weight; private int yearOfBirth; public static int CompareName(object p1, object p2) { return string.Compare(((Person)p1).name, ((Person)p2).name); } }
  • 41. Solution 18 16/01/2011 //… Person[] persons= new Person[4]; persons[0] = new Person(“QuyMui",20,2004); persons[1] = new Person(“Ha Giang",62,1978); persons[2] = new Person(“Ngoc Thao",47, 1979); persons[3] = new Person(“Ha Nam",4,2009); // create instance of delegate refer to Person.CompareName CompareObjcmp = new CompareObj(Person.CompareName); HaGLib.Sort(persons,cmp); Class contains static Sort method
  • 44. Event Cơ chế thông điệp giữa các lớp hay các đối tượng Có thể thông báo cho lớp khác biết được khi một lớp có phát sinh điều gì đó Publisher: lớp phát sinh sự kiện Subscriber: lớp nhận hay xử lý khi sự kiện xảy ra 21 16/01/2011
  • 45. Event Trong môi trường giao diện GUIs (Graphical User Interfaces: GUIs): Button đưa ra sự kiện “Click”, cho phép lớp khác có thể đáp ứng (xử lý) khi sự kiện này xảy ra. VD: Button “Add” trong Form, khi sự kiện click xảy ra thì Form thực hiện lấy dữ liệu từ các TextBox đưa vào ListBox… 22 16/01/2011
  • 46. Event Một lớp publish tập các event cho phép các lớp khác subscribe Button là lớp publish đưa ra event: click Form là lớp subscribe có phần xử lý riêng khi “click” của Button kích hoạt. 23 16/01/2011 event subscribe Thông báo publish B A Đăng ký C
  • 47. Event & Delegate Sự kiện trong C# được thực thi nhờ uỷ thác Lớp publishing định nghĩa ủy thác Những lớp subscribing phải thực thi Khi sự kiện xuất hiện thì phương thức của lớp subscribing được gọi thông qua uỷ thác. Phương thức để xử lý sự kiện gọi là trình xử lý sự kiện (event handler) 24 16/01/2011
  • 48.
  • 50. Thamsố 1: nguồnphátsinhsựkiện, đâychínhlàđốitượng publisher
  • 53.
  • 55. Các lớp muốn xử lý khi sự kiện OnEventName phát sinh thì phải thực thi event handlerpublic delegate void HandlerName(object obj, EventArgsarg); public event HandlerName OnEventName;
  • 56. Minh họa Xây dựng 1 lớp thực hiện yêu cầu: “cứ mỗi giây sẽ phát sinh 1 sự kiện” Cho phép 2 lớp khác đăng ký xử lý sự kiện này, mỗi lớp có cách xử lý riêng: Lớp A: hiển thị thời gian theo “mô phỏng đồng hồ analog” Lớp B: hiển thị thời gian theo “mô phỏng đồng hồ digital” 27 16/01/2011
  • 57. Minh họa Tạo một lớp Clock: Khai báo một event: OnSecondChange Một phương thức Run: cứ 1s thì phát sinh sự kiện OnSecondChange Tạo 2 lớp: AnalogClock và DigitalClock nhận xử lý sự kiện OnSecondChange của lớp Clock 28 16/01/2011
  • 58. Minh họa Khai báo delegate xử lý event 29 16/01/2011 Tên delegate xửlýsựkiện delegate void SecondChangeHandler(object clock, EventArgs info); Đối tượng phát sinh event Tham số kiểu EventArgs
  • 59. Minh họa Khai báo event có hàm xử lý mô tả trên 30 16/01/2011 Kiểu delegate event SecondChangeHandlerOnSecondChange; Tên của event Từ khóa event: thể hiện cơ chế publishing & subscribing
  • 60. Minh họa Kích hoạt sự kiện 31 16/01/2011 Kiểm tra xem có hàm xử lý được đăng ký hay không? if (OnSecondChange != null) OnSecondChange(this, new EventArgs()); Gọi hàm xử lý sự kiện đã đăng ký
  • 61. Minh họa 32 16/01/2011 public class Clock{ public delegate void SecondChangeHandler(object clock, EventArgs info); public event SecondChangeHandlerOnSecondChange; public void Run() { while (true){ Thread.Sleep(1000); if (OnSecondChange != null) OnSecondChange(this, new EventArgs()); } } }
  • 62. Minh họa Lớp DigitalClock Định nghĩa trình xử lý sự kiện của Clock Đúng mô tả delegate hàm xử lý của lớp Clock Thực hiện một số thao tác riêng của DigitalClock Đăng ký xử lý với trình xử lý sự kiện trên khi có sự kiện OnSecondChange của Clock Chức năng đăng ký với lớp Clock là có xử lý khi sự kiện OnSencondChange của Clock phát sinh Ủy thác cho lớp Clock sẽ gọi trình xử lý định nghĩa bên trên của DigitalClock 33 16/01/2011
  • 63. Minh họa Trình xử lý của DigitalClock 34 16/01/2011 Đối tượng phát sinh sự kiện Tên của trình xử lý public void Show(object obj, EventArgs args) { DateTime date = DateTime.Now; Console.WriteLine("Digital Clock: {0}:{1}:{2}", date.Hour, date.Minute, date.Second); }
  • 64. Minh họa Đăng ký xử lý sự kiện 35 16/01/2011 Đối tượng này sẽ phát sinh sự kiện public void Subscribe(Clock theClock) { theClock.OnSecondChange += new Clock.SecondChangeHandler(Show); } Ủy thác phương thức Show choOnSecondChange
  • 65. Minh họa 36 16/01/2011 public class DigitalClock { public void Subscribe(Clock theClock) { theClock.OnSecondChange += new Clock.SecondChangeHandler(Show); } public void Show(object obj, EventArgs args) { DateTime date = DateTime.Now; Console.WriteLine("Digital Clock: {0}:{1}:{2}", date.Hour, date.Minute, date.Second); } }
  • 66. Minh họa Lớp AnalogClock Định nghĩa trình xử lý sự kiện của Clock Đúng mô tả delegate hàm xử lý của lớp Clock Thực hiện một số thao tác riêng của AnalogClock Đăng ký xử lý với trình xử lý sự kiện trên khi có sự kiện OnSecondChange của Clock Chức năng đăng ký với lớp Clock là có xử lý khi sự kiện OnSencondChange của Clock phát sinh Ủy thác cho lớp Clock sẽ gọi trình xử lý định nghĩa bên trên của AnalogClock 37 16/01/2011
  • 67. Minh họa 38 16/01/2011 public class AnalogClock { public void Subscribe(Clock theClock) { theClock.OnSecondChange += new Clock.SecondChangeHandler(Show); } public void Show(object obj, EventArgs args) { DateTime date = DateTime.Now; Console.WriteLine("Analog Clock: {0}:{1}:{2}",date.Hour,date.Minute,date.Second); } }
  • 68. Minh họa Minh họa cơ chế event 39 16/01/2011 public class Tester{ public static void Main(){ Clock myClock = new Clock(); AnalogClock c1 = new AnalogClock(); DigitalClock c2 = new DigitalClock(); c1.Subscribe(myClock); c2.Subscribe(myClock); myClock.Run(); } } Đăng ký xử lý sự kiện của đối tượng myClock! Phát sinh sự kiện
  • 69. Minh họa 40 16/01/2011 public static void Main() { Clock myClock = new Clock(); AnalogClock c1 = new AnalogClock(); DigitalClock c2 = new DigitalClock(); myClock.OnSecondChange += new Clock.SecondChangeHandler(c1.Show); myClock.OnSecondChange += new Clock.SecondChangeHandler(c2.Show); myClock.Run(); } Đượckhông?
  • 71.
  • 75. Khiphátsinhsựkiện, truyềnthờigianhiệnhành  lớp subscribing sẽsửdụngthamsốnày
  • 77. Minh họa EventArgs Tạo lớp chứa tham số truyền cho trình xử lý sự kiện Lớp dẫn xuất từ EventArgs Chứa các thông tin về: giờ, phút, giây Bắt buộc phải dẫn xuất từ EventArgs Do mô tả của trình xử lý sự kiện là tham số thứ 2 phải là lớp dẫn xuất từ EventArgs! 43 16/01/2011
  • 78. Minh họa EventArgs 44 16/01/2011 public class TimeEventArgs : EventArgs { public readonly int Second; public readonly int Minute; public readonly int Hour; public TimeEventArgs(int s, int m, int h) { Second = s; Minute = m; Hour = h; } }
  • 79. Minh họa EventArgs Trong lớp Clock khai báo trình xử lý sự kiện như sau 45 16/01/2011 public delegate void SecondChangeHandler(object obj, TimeEventArgs arg); Sử dụng tham số thứ hai có kiểu TimeEventArgs
  • 80. Minh họa EventArgs Khi kích hoạt sự kiện thì truyền tham số {giờ, phút, giây} 46 16/01/2011 public void Run() { while (true) { Thread.Sleep(1000); if (OnSecondChange != null) { DateTime date = DateTime.Now; TimeEventArgs timeArg = new TimeEventArgs(date.Second, date.Minute, date.Hour); OnSecondChange(this, timeArg); } } }
  • 81. Minh họa EventArgs Các lớp DigitalClock và AnalogClock: sử dụng tham số truyền vào 47 16/01/2011 public class AnalogClock { public void Subcribe(Clock theClock) { theClock.OnSecondChange += new Clock.SecondChangeHandler(Show); } public void Show(object obj, TimeEventArgs timeArg) { Console.WriteLine("Analog Clock: {0}:{1}:{2}", timeArg.Hour, timeArg.Minute, timeArg.Second); } }
  • 82. Minh họa EventArgs Các phần khác còn lại tương tự như minh họa 1 48 16/01/2011 Demo Eventc
  • 83. Event Bài tập 49 16/01/2011 Viết một chương trình đơn giản minh họa quản lý tài khoản ATM: khi rút tiền hoặc chuyển tiền thì hệ thống sẽ gởi tự động tin nhắn đến handphone của chủ tài khoản. Hướng dẫn: - Khi rút tiền hoặc chuyển tiền xong: phát sinh sự kiện “đã rút tiền” hoặc “đã chuyển tiền”
  • 84.
  • 87. Multi cast delegate thamchiếuđếnnhiềuphươngthức
  • 88. Multi cast là delegate cógiátrịtrảvềphảilàvoid
  • 91. Tóm tắt Event Event được thực thi thông qua delegate Thể hiện sự truyền thông qua lại Lớp phát sinh sự kiện: publishing Những lớp xử lý sự kiện: subscribing Thành phần quan trọng trong GUIs 51 16/01/2011
  • 92. Delegate & Event 52 16/01/2011 ?