您的位置:首页 > 编程语言 > C语言/C++

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

2009-01-13 23:28 190 查看
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));
}
}
}

其目的,都是实现,自己调用了回调函数,具体要做什么,要由回调函数说了算。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: