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);
            }
        }
    }
} 

C#回调函数_第1张图片










你可能感兴趣的:(C#,C#,回调函数,回调,dll,CSharp)