简介
类型安全机制的实现原来采用的是C风格的回调(callback)函数,而.NET Framework引入了委托和事件来替代原来的方式;它们被广泛地使用。我们在这里尝试使用标准C++来实现与之类似的功能,这样我们不但可以对这些概念有一个更好的认识,而且同时还能够体验C++的一些有趣的技术。
C#中的委托与事件关键字
首先我们来看一个简单的C#程序(下面的代码略有删节)。执行程序的输出结果如下显示:
SimpleDelegateFunction called from Ob1,
string=Event fired!
Event fired!(Ob1): 3:49:46 PM on
Friday, May 10, 2002
Event fired!(Ob1): 1056318417
SimpleDelegateFunction called from Ob2,
string=Event fired!
Event fired!(Ob2): 3:49:46 PM on
Friday, May 10, 2002
Event fired!(Ob2): 1056318417
所有这些都源于这样一行代码:dae.FirePrintString("Event fired!");
在利用C++来实现这些功能时,我模仿了C#的语法并完全按照功能的要求进行开发。
namespace DelegatesAndEvents { class DelegatesAndEvents { public delegate void PrintString(string s); public event PrintString MyPrintString; public void FirePrintString(string s) { if (MyPrintString != null)MyPrintString(s); } }
class TestDelegatesAndEvents { [STAThread] static void Main(string[] args) { DelegatesAndEvents dae =new DelegatesAndEvents(); MyDelegates d = new MyDelegates(); d.Name = "Ob1"; dae.MyPrintString +=new DelegatesAndEvents.PrintString(d.SimpleDelegateFunction); // ... more code similar to the // above few lines ... dae.FirePrintString("Event fired!"); } } class MyDelegates { // ... "Name" property omitted... public void SimpleDelegateFunction(string s) { Console.WriteLine("SimpleDelegateFunction called from {0}, string={1}", m_name, s); } // ... more methods ... } } |
<  
1/2 1 2 下一页 尾页 |