讲解C++与C#里的 回调。

 C++ 有一段时间没用了。先引用一篇文章: http://www.cppblog.com/SpringSnow/archive/2008/12/07/68770.aspx

typedef void (*PF)();

void func()
{
    printf(
"func") ;
}

void caller( PF pf)
{
  pf();
}

int _tmain(int argc, _TCHAR* argv[])
{
    caller( func ) ;
    
    
return 0;
}

至于 C# ,也差不到哪去。只是写法看起来更优雅一些。

namespace ConApp
{
    
public delegate void func_delegate();

    
public class Test
    {
        
public event func_delegate FuncEvent;   //也可以不定义。  用 Event 定义是其中方式之一。
        public void CallerForEvent()
        {
            FuncEvent();
        }

        
public void CallerForDeleagate(func_delegate CallBack)
        {
            CallBack();
        }
    }


    
/// <summary>
    
/// Program
    
/// </summary>
    public class Program
    {
        
        
public void TestCallBack()
        {
            Console.WriteLine(
"Hello , In My Program !");
        }

        
/// Main
        
/// </summary>
        
/// <param name="args">string[] args)</param>
        static void Main(string[] args)
        {
            
// Event 方式调用。
            Test test = new Test();
            test.FuncEvent 
+= new func_delegate(
                
delegate()
                {
                    Console.WriteLine(
" New Function !") ;
                }
                );
            test.CallerForEvent() ;

            
// 委托方式调用。
            test.CallerForDeleagate(new func_delegate(new Program().TestCallBack));
        }
    }
}

其目的,都是实现,自己调用了回调函数,具体要做什么,要由回调函数说了算。

alarm   作者:NewSea     出处:http://newsea.cnblogs.com/    QQ,MSN:iamnewsea@hotmail.com

  如无特别标记说明,均为NewSea原创,版权私有,翻载必纠。欢迎交流,转载,但要在页面明显位置给出原文连接。谢谢。
原文地址:https://www.cnblogs.com/newsea/p/1375223.html