Tải bản đầy đủ (.pdf) (52 trang)

Delegate & Event - Nguyen Ha Giang potx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (507.48 KB, 52 trang )

Delegate & Event
Nguyen Ha Giang
1Nguyen Ha Giang -200909/09/2012
Table of Contents
§ Delegate
§ 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
§ Summary
2Nguyen Ha Giang -2009
09/09/2012
Definition of delegate
• Class package some signature methods
• 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 methods
3Nguyen Ha Giang -2009
09/09/2012
Definition of delegate
• Delegates define a method signature


– 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 instance
4Nguyen Ha Giang -2009
09/09/2012
Working with delegates
• Define a delegate in namespace or class
5Nguyen Ha Giang -2009
09/09/2012
public delegate void MyDelegate1(intx, inty);
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
6Nguyen Ha Giang -2009
09/09/2012
class Test
{
public void Method1(inta, intb)
{
// body of method
}


}
Test t = new Test();
MyDelegate1 d1 = new MyDelegate1( t.Method1);
public delegate void MyDelegate1(intx, inty);
Working with delegate
• Instance of delegate
7Nguyen Ha Giang -2009
09/09/2012
class Test
{

public static string Method2(float f)
{
// body of method
}
}
MyDelegate2 d2 = new MyDelegate2( Test.Method2);
public delegate string MyDelegate2(float f);
Working with delegate
• Invoking delegates
8Nguyen Ha Giang -2009
09/09/2012
intx = 5, y = 10;
d1(x, y);
d1(10, 20); inty = 2;
d1(100, y);
d1
float f =0.5f;
string s = d2(f);

string s = d2(100);
d2
Invoking multiple delegate
• Using only for delegates with no return value
9Nguyen Ha Giang -2009
09/09/2012
class Test
{
public delegate voidMyDelegate3(intn1, intn2);
static void Print(intx, inty)
{
Console.WriteLine("x={0}, y={1}", x, y);
}
static void Sum(inta, intb)
{
Console.WriteLine("Tong={0}", a + b);
}
// (cont)…
}
No return
Invoking multiple delegate
10Nguyen Ha Giang -2009
09/09/2012
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
11Nguyen Ha Giang -2009
09/09/2012
Problem
12Nguyen Ha Giang -2009
09/09/2012
How to build the
Sort method for
array of objects of
any data type?
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?
13Nguyen Ha Giang -2009
09/09/2012
Which criteria for
comparing?
Solution
• Objects have to define their order (Compare)
• Using delegate to pass “compare method” into

Sort method.
14Nguyen Ha Giang -2009
09/09/2012
void Sort(object[] list, CompareObjcmp)
This delegate refers to Compare method of
class which need to sort.
Solution
• Define delegate CompareObj for Sort method
15Nguyen Ha Giang -2009
09/09/2012
public delegate int CompareObj(object o1, object o2)
-1 : o1 “<“ o2
0 : o1 “=“ o2
1 : o1 “>” o2
Two objects passed
Name of delegate type
Solution
16Nguyen Ha Giang -2009
09/09/2012
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] );
}
Definition of Sort method
Delegate will refer to compare
method of class
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
17Nguyen Ha Giang -2009
09/09/2012
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
18Nguyen Ha Giang -2009
09/09/2012
//…
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
CompareObj cmp = new CompareObj(Person.CompareName);
HaGLib.Sort( persons, cmp );
Class contains static Sort method

19Nguyen Ha Giang -2009
09/09/2012
20Nguyen Ha Giang -2009
09/09/2012
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
21Nguyen Ha Giang -2009
09/09/2012
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…
22Nguyen Ha Giang -2009
09/09/2012
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.
23Nguyen Ha Giang -2009
09/09/2012
A
B
C
event
publish
subscribe
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)
24Nguyen Ha Giang -2009
09/09/2012
Event & Delegate
• Trìnhxửlýsựkiệntrong.NET Framework
đượcmôtảnhư sau:
– Trả về giátrị void
– Thamsố1: nguồnphátsinhsựkiện, đâychínhlà
đốitượngpublisher
– Thamsố2: là đốitượngthuộclớpdẫnxuấttừ
EventArgs
• Phảithựchiệntrìnhxửlýsựkiệntheo đúng

mẫutrên!
25Nguyen Ha Giang -2009
09/09/2012

×