zoukankan      html  css  js  c++  java
  • delegate(代理,委托)

    下面的例子描述了delegate的声明,初始化和调用:

    public partial class Form1 : Form

    {

    // declares a delegate, it has one parameter.

    delegate void help(string message);

    public Form1()

    {

    InitializeComponent();

    // anonymous method.

    this.MouseClick += delegate(object sender, MouseEventArgs e)

    {

    MessageBox.Show("hello world");

    };

    }

    private void Form1_Load(object sender, EventArgs e)

    {

    // 2 ways to initialize the delegate

    // 1.decides what to do with this delegate, here using a named method "ShowMessage".

    help h1 = new help(Form1.ShowMessage);   // also we can write it as "help h1 = Form1.ShowMessage", they are the same meaning.

    // 2.decides what to do with this delegate, here using a anonymous method.

    help h2 = delegate(string message) { MessageBox.Show(message); };

    // 2 ways to call the delegate

    // 1.call the delegate

    h1.Invoke("message from delegate1");

    // 2.call the delegate

    h2("message from delegate2");

    }

    private static void ShowMessage(string message)

    {

    MessageBox.Show(message);

    }

    }
    接下来总结一下常用的事件的注册方法,这里我列出了四种方式:

    Code

    注册这些事件如下:

    Code

    下面介绍三个常用的delegate:Func,Action和Predicate

    1. Func<T,TResult> delegate:

    语法:public delegate TResult Func<T, TResult>(T arg);

    用它封装一个方法,该方法只有一个参数,T是参数的类型,TResult是返回值的类型。

    例如:

    Code

    2. Action<T>, Action<T1, T2>,Action 等等
     它封装一个方法,带有一个或多个参数,但是没有返回值。

     它与Func的区别就是Func有返回值,Action无返回值。

    3. Predicate<T>

    predicate的意思是断定为,预言成..., 它封装了一个方法,带有一个参数,返回值是bool型。

  • 相关阅读:
    区间dp_学习笔记
    状态压缩dp_学习笔记
    第十一届蓝桥杯C/C++ J题网络分析(带权并查集水题)
    状态机dp学习笔记_AcWing
    洛谷P4052 [JSOI2007]文本生成器(AC自动机+DP)
    洛谷P5840 [COCI2015]Divljak (AC自动机+fail树上dfs序+树上差分线段树维护)
    洛谷P3401 [USACO12JAN]Video Game G(AC自动机+记忆化搜索)
    HDU3613 Best Reward (exKMP/manacher)
    洛谷P2375 [NOI2014]动物园(KMP+倍增优化)
    ICPC2017南宁站题解(A,E,F,H,I,J,L,M)
  • 原文地址:https://www.cnblogs.com/bear831204/p/1289960.html
Copyright © 2011-2022 走看看