zoukankan      html  css  js  c++  java
  • 对回调函数的理解

    1 public sealed class Timer : MarshalByRefObject, IDisposable
    2     {
    3         
    4         [SecuritySafeCritical]
    5         public Timer(TimerCallback callback);
    6     }

    回调函数就是在函数的参数列表中传入一个函数,例如在C#中通过委托传入一个函数,然后在函数体内部执行传入的函数

    --------------------2018-03-16-----------分割线-----------------------------

    回调函数:

    在某个类中定义某个public的函数,但是这个类的对象并不去调用他,而是由另外一个类内部 或者对象去调用他

    这样子就叫做回调函数。

    上面的timer也是如此,定义一个方法不去使用,而是传给timer类,通过挂接到里面的委托,在类的内部去调用他。

    代码:FrmOther.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace UseDelegate
    {
        public partial class FrmOther : Form
        {
            public FrmOther()
            {
                InitializeComponent();
            }
    
            public void ShowCount(int count)//这个方法并没哟被这个类调用
            {
                label1.Text = count.ToString();
            }
            private void label1_Click(object sender, EventArgs e)
            {
    
            }
        }
    }

    FrmMain.cs

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    
    namespace UseDelegate
    {
    
        public partial class FrmMain : Form
        {
            private Action<int> ReceiverMethods;//定义一个用于挂接回调函数的委托
            public FrmMain()
            {
                InitializeComponent();
            }
    
            private FrmOther other = null;
            private int count = 0;
            private void NewForm()
            {
                other = new FrmOther();
                other.Show();
            }
            private void btnNewFrm_Click(object sender, EventArgs e)
            {
                NewForm();
                ReceiverMethods += other.ShowCount;//在这里挂接FrmOther的用于回调的函数
            }
    
            private void btnAdd_Click(object sender, EventArgs e)
            {
                if (ReceiverMethods != null)
                {
                    ReceiverMethods(++count);//在这里执行回调函数
                }
            }
        }
    }
  • 相关阅读:
    树形dp--P2014 [CTSC1997]选课
    背包变形--P1759 通天之潜水
    区间dp--P1880 [NOI1995]石子合并
    动态规划--P2758 编辑距离
    筛法--CF449C Jzzhu and Apples
    BZOJ3998: [TJOI2015]弦论(后缀自动机,Parent树)
    BZOJ3530: [Sdoi2014]数数(Trie图,数位Dp)
    BZOJ1444: [Jsoi2009]有趣的游戏(Trie图,矩乘)
    BZOJ1195: [HNOI2006]最短母串(Trie图,搜索)
    BZOJ3238: [Ahoi2013]差异(后缀数组)
  • 原文地址:https://www.cnblogs.com/c-supreme/p/8391235.html
Copyright © 2011-2022 走看看