码迷,mamicode.com
首页 > 其他好文 > 详细

对回调函数的理解

时间:2018-03-16 18:47:56      阅读:153      评论:0      收藏:0      [点我收藏+]

标签:ble   window   one   windows   using   定义   分割   receive   for   

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);//在这里执行回调函数
            }
        }
    }
}

 

对回调函数的理解

标签:ble   window   one   windows   using   定义   分割   receive   for   

原文地址:https://www.cnblogs.com/c-supreme/p/8391235.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!