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();
}