C#回调函数

参考文章:http://blog.csdn.net/echo_qiang/article/details/6996595

http://www.cnblogs.com/birdshover/archive/2008/01/07/1029471.html

------------------------------------------------------------------------------------------------------------

关于回调函数说说我的一点理解吧。

1. 回调函数的实现一般在exe程序中。

2.回调函数的调用一般在dll文件中。

3.dll要调用exe中的回调函数,exe必须把回调函数的地址传递给dll。

4.dll有了exe中回调函数的原型和地址,就可以随时调用(触发)该回调函数了。

5.有了1到4,不同编程语言的回调机制,万变不离其宗,一通百通?。

-------------------------------------------------------------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CallBackFunction
{
    class Program
    {
        static void Main(string[] args)
        {
            Program prog = new Program();   // 在静态函数Main中调用非静态方法时,
                                            // 必须先实例化该类对象,方可调用Add方法 
            DllClass dll = new DllClass();

            dll.SetAddCallBack(prog.Add);   // 设置回调
            dll.CallAdd();                  // 触发回调
            Console.Read();                 // 暂停程序
        }

        // 回调函数
        private int Add(int a, int b)
        {
            int c = a + b;
            Console.WriteLine("Add被调用了,a+b={0}", c);
            return c;
        }
    }


    class DllClass  // 假设此类封装在dll中
    {
        // 声明回调函数原型,即函数委托了
        public delegate int Add(int num1, int num2);

        public Add OnAdd = null;   // 此处相当于定义函数指针了

        // 设置回调函数地址
        public void SetAddCallBack(Add add)
        {
            this.OnAdd = add;
        }

        // 调用回调函数
        public void CallAdd()
        {
            if (OnAdd != null)
            {
                OnAdd(1, 99);
            }
        }
    }
} 











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

friendan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值