C++/Cli中的事件对象,其实就是一个栈,+=gcnew中事件,再-=gcnew的委托是依次从栈顶消除的。哪怕是同一个类型的委托。
代码示例如下:
// eventTest.cpp: 主项目文件。 #include "stdafx.h" using namespace System; // C3918_3.cpp // compile with: /clr /c using namespace System; public delegate void del(); public ref class A { public: static int i=0; event del^ e { void add(del ^handler ) { d += handler; } void remove(del ^handler) { d -= handler; } void raise() { d(); } } del^ d; void f() { i=i+1; Console::WriteLine("hello"+i); } A() { //e = gcnew del(this, &A::f); // C3918 // try the following line instead e += gcnew del(this, &A::f); e += gcnew del(this, &A::f); e -= gcnew del(this, &A::f); } }; int main() { A^ a=gcnew A; a->e(); Console::ReadLine(); }
本文介绍C++/CLI中事件对象的工作原理,通过一个具体示例展示如何使用+=和-=操作符来添加和移除事件处理程序。文章解释了事件对象作为一个栈的数据结构特性,并说明了不同类型的委托是如何被添加和移除的。
3892

被折叠的 条评论
为什么被折叠?



