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

  • 相关阅读:
    (转)python3 计算字符串、文件md5值
    CF1398D Colored Rectangles(DP)
    Colab运行GitHub代码
    Pytorch错误解决
    SAP内部订单
    料工费
    摘抄,泛起内心的一丝波澜
    审计意见类型
    生产订单设置自动倒冲
    SAP常用事务码及规则tcode
  • 原文地址:https://www.cnblogs.com/bear831204/p/1289960.html
Copyright © 2011-2022 走看看