简介
类型安全机制的实现原来采用的是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 ... } } |




