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);//在这里执行回调函数
                }
            }
        }
    }
  • 相关阅读:
    AUDIOqueue 为什么会播放一段时间就听不到声音
    逆序一位数数组求和
    求数组中两数之和等于target的两个数的下标
    iOS获取崩溃日志
    如何看iOS崩溃日志
    关于iOS刷新UI需要在主线程执行
    iOS内置麦克风选择方法
    贝叶斯深度学习-概述
    空间统计(Spatial Statistics)学习笔记(一)— 概述
    重采样技术—Bootstrap
  • 原文地址:https://www.cnblogs.com/c-supreme/p/8391235.html
Copyright © 2011-2022 走看看