delegate_event trong c#

Upload: mantran

Post on 09-Jan-2016

3 views

Category:

Documents


0 download

DESCRIPTION

Delegate và event

TRANSCRIPT

  • C ch Delegate & Event

  • 2

    N i dungN i dung Delegate

    Khi ni m delegate Th c thi delegate Multicast delegate Gi i php cho hm Sort t ng qut

    Event Khi ni m event Event & delegate C ch publishing & subscribing Minh h a c ch event

  • 3

    DelegateDelegate

    L p ng gi cc ph ng th c (method signature) Dng trong event-handling model c a C# c tnh

    Type safe Object oriented mechanism

    Delegate l class: C instance C th ch a nh ng tham chi u n 1 hay nhi u method

  • 4

    DelegateDelegate

    M t delegate nh ngha m t signature Return type Sequence of parameter types

    T t c cc method c cng signature c th c add vo th hi n c a delegate

    Delegate instance c m t danh sch cc tham chi u method Cho php add (+) cc method C th remove (-) cc method

  • 5

    Define delegateDefine delegate

    public delegate void MyDelegate1(int x, int y)

    Delegate cho d ng hm: void Method( int, int )

    public delegate string MyDelegate2(float f)

    Delegate cho d ng hm: string Method( float )

  • 6

    Instance delegateInstance delegate

    public void Method1(int x, int y){

    }MyDelegate1 del1 = new MyDelegate1(Method1);

    public string Method2(float f){

    }MyDelegate2 del2 = new MyDelegate2(Method2);

  • 7

    Call DelegateCall Delegate

    int x = 5, y = 10;int x = 5, y = 10;del1(x, y);del1(x, y); del1(10, 20);del1(10, 20);

    int y = 2;int y = 2;del1(100, y);del1(100, y);

    G i del1G i del1

    float f =0.5f;float f =0.5f;string s;string s;s = del2(f);s = del2(f);

    string s = del2(100f);string s = del2(100f);

    G i del2G i del2

  • 8

    Multi CastMulti Cast

    void Print(int x,int y) {void Print(int x,int y) {Console.WriteLine(x = {0}, y = {1}, x, y);Console.WriteLine(x = {0}, y = {1}, x, y);

    }}void Sum(int x, int y) {void Sum(int x, int y) {

    Console.WriteLine(Tong = {0}, x+y);Console.WriteLine(Tong = {0}, x+y);}}

    MyDelegate1 mulDel = new MyDelegate1(Print);MyDelegate1 mulDel = new MyDelegate1(Print);mulDel += new MyDelegate1(Sum);mulDel += new MyDelegate1(Sum);

    mulDel(5, 10); mulDel(5, 10);

    mulDel -= new MyDelegate1(Print);mulDel -= new MyDelegate1(Print);mulDel(5,10);mulDel(5,10);

  • 9

  • 10

    ProblemProblem

    Xy d ng hm Sort t ng qut cho m ng i t ng c ki u b t

    k