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);//在这里执行回调函数
                }
            }
        }
    }
  • 相关阅读:
    SQL Server 存储过程
    FindControl的详细介绍
    Transaction-SQL 游标
    硬盘安装工具nt6 hdd installer无法卸载的问题
    Some question about Source Tree
    java 简单加密
    java 多态与多重继承
    构造方法和方法的重载
    64位WIN7上安装11G R2 ,PLSQL的配置方法
    语录(排名不分先后)
  • 原文地址:https://www.cnblogs.com/c-supreme/p/8391235.html
Copyright © 2011-2022 走看看