Quantcast
Channel: CSDN博客推荐文章
Viewing all articles
Browse latest Browse all 35570

Delegate

$
0
0
  • If lower layer (DB) wants to callback higher layer (UI),we can define a delegate in lower layer,then in higher layer we instantiate that delegate with the implementation method in higher layer,for example,
lower layer:      public delegate void MyDelegate();
           public static MyDelegate MyDel= null;

higher layer:lower.MyDel = DelImpl;

      void DelImpl()

     {

//implementation

     }


  • We can use named methods, anonymous methods or lambda expression to instantiate the delegate:
    • Named method

delegate void Del();

void DoWork(); // support both instance method and static method

Del d = DoWork; //  Is equal to "Del d = new Del(DoWork);", but simpler.

  • Anonymous method

delegate void Del();

Del d = delegate() {/*....code block...*/};

  • Lambda expression (a type of anonymous method)
delegate int Del(int x);

Del d = (x)=> {return x * x;}


  • Multicast delegate: (+: add object to delegate, -:remove object from delegate, execute in order, only can combine the delegate with same type), for example:
   delegate void Del();
   void Hello();
   void World();
   Del d1 = Hello;
   Del d2 = World;
   Del d3 = d1 + d2;
   Del d4 = d3 - d2;
   d3(); // first call Hello(), then call World();
   d4(); // only call Hello();
作者:chuwachen 发表于2013-2-1 15:55:39 原文链接
阅读:20 评论:0 查看评论

Viewing all articles
Browse latest Browse all 35570

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>