欢迎来到天天文库
浏览记录
ID:1692707
大小:128.50 KB
页数:27页
时间:2017-11-13
《使用c++深入研究.net的委托与事件》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、使用C++深入研究.NET的委托与事件撰文J.DanielSmith 翻译曾毅最后更新:2004年3月14日想要真正掌握委托与事件最好的方法便是你自己来实现它们—使用以前的纯C++。简介类型安全机制的实现原来采用的是C风格的回调(callback)函数,而.NETFramework引入了委托和事件来替代原来的方式;它们被广泛地使用。我们在这里尝试使用标准C++来实现与之类似的功能,这样我们不但可以对这些概念有一个更好的认识,而且同时还能够体验C++的一些有趣的技术。C#中的委托与事件关键字首先我们来看一
2、个简单的C#程序(下面的代码略有删节)。执行程序的输出结果如下显示:SimpleDelegateFunctioncalledfromOb1,string=Eventfired!Eventfired!(Ob1):3:49:46PMonFriday,May10,2002Eventfired!(Ob1):1056318417SimpleDelegateFunctioncalledfromOb2,string=Eventfired!Eventfired!(Ob2):3:49:46PMonFriday,May10,2
3、002Eventfired!(Ob2):1056318417 所有这些都源于这样一行代码:dae.FirePrintString("Eventfired!");在利用C++来实现这些功能时,我模仿了C#的语法并完全按照功能的要求进行开发。namespaceDelegatesAndEvents{classDelegatesAndEvents{publicdelegatevoidPrintString(strings);publiceventPrintStringMyPrintString;publicvoid
4、FirePrintString(strings){if(MyPrintString!=null)MyPrintString(s);}}classTestDelegatesAndEvents{[STAThread]staticvoidMain(string[]args){DelegatesAndEventsdae=newDelegatesAndEvents();MyDelegatesd=newMyDelegates();d.Name="Ob1";dae.MyPrintString+=newDelegatesA
5、ndEvents.PrintString(d.SimpleDelegateFunction);//...morecodesimilartothe//abovefewlines...dae.FirePrintString("Eventfired!");}}classMyDelegates{//..."Name"propertyomitted...publicvoidSimpleDelegateFunction(strings){Console.WriteLine("SimpleDelegateFunction
6、calledfrom{0},string={1}",m_name,s);}//...moremethods...}} C++中的类型安全函数指针对于“老式方法”的批判之一便是它们不是类型安全的[1]。下面的代码证明了这个观点:typedefsize_t(*FUNC)(constchar*);voidprintSize(constchar*str){FUNCf=strlen;(void)printf("%sis%ldchars",str,f(str));}voidcrashAndBurn(constc
7、har*str){FUNCf=reinterpret_cast(strcat);f(str);} 代码在[2]中可以找到。当然,在你使用reinterpret_cast的时候,你可能会遇到麻烦。如果你将强制转换(cast)去掉,C++编译器将报错,而相对来说更为安全的static_cast也不能够完成转换。这个例子也有点像比较苹果和橙子,因为在C#中万事万物皆对象,而reinterpret_cast就相当于一种解决方式。下面的这个C++程序示例将会采取使用成员函数指针的方法来避免使用rein
8、terpret_cast:structObject{};structStr:publicObject{size_tLen(constchar*str){returnstrlen(str);}char*Cat(char*s1,constchar*s2){returnstrcat(s1,s2);}}; typedefsize_t(Object::*FUNC)(constchar*);voidprintSize(con
此文档下载收益归作者所有