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型。

  • 相关阅读:
    [College] C++字符串读入与进制转化-关于《实践教程》P10[程序]的一些总结
    [College] 二进制与机器数的几种形式
    [College] Hello World!
    [SinGuLaRiTy] 复习模板-数学
    ByteCTF 2020 KOP Writeup
    【题解】电子科技大学第十八届 ACM 程序设计竞赛
    【逆向】某 VR 驱动分析过程
    物联网框架 IoTivity 中间人攻击分析
    批处理工具 CAPI 逆向分析之 API Call
    DASCTF 2020 六月赛 Reverse Writeup
  • 原文地址:https://www.cnblogs.com/bear831204/p/1289960.html
Copyright © 2011-2022 走看看