[英]How do I assign an event handler to an event in C++/CLI?
How do I add "events" to an "event"/delegate? 如何将“事件”添加到“事件”/委托? What is the syntax?
语法是什么? Is it the same in C++/CLI and in C#?
它在C ++ / CLI和C#中是一样的吗?
1: If underlyng delgate of the event is a custom one you define yourself that is a class memeber (example from MSDN ): 1:如果事件的underlyng delgate是自定义的,那么你定义自己是一个类memeber(来自MSDN的例子):
delegate void Del(int, float);
ref class EventReceiver {
public:
void Handler(int i , float f) { }
};
myEventSource->MyEvent += gcnew Del(myEventReceiver, &EventReceiver::Handler);
2: If the underlying delegate is a global handler and has the standard signature for .NET events (object + event args) (from DPD answer): 2:如果底层委托是全局处理程序并且具有.NET事件的标准签名(对象+事件args)(来自DPD答案):
delegate void MyOwnEventHandler(Object^ sender, EventArgs^ e) { }
myEventSource->MyEvent += gcnew EventHandler(MyOwnEventHandler);
3: If the underlying delegate has the standard signature for .NET events and the event handler is a class method: 3:如果底层委托具有.NET事件的标准签名,并且事件处理程序是类方法:
ref class EventReceiver {
public:
void Handler(Object^ sender, EventArgs^ e) { }
};
myEventSource->MyEvent += gcnew EventHandler(myEventReceiver, &EventReceiver::Handler);
4: Using System::EventHandler generic (that takes a MyEventArgs args parameter) as the underlying delegate: 4:使用System :: EventHandler泛型(它采用MyEventArgs args参数)作为底层委托:
ref class EventReceiver {
public:
void Handler(Object^ sender, MyEventArgs^ e) { }
};
myEventSource->MyEvent += gcnew EventHandler<MyEventArgs^>(this, &EventReceiver::DataReceived);
In c# , you do it with the +=
operator: 在c#中 ,您使用
+=
运算符:
someObj.SomeEvent += new EventHandler(Blah_SomeEvent);
... ...
private void Blah_SomeEvent(object sender, EventArgs e)
{
}
It has been a long time since I posted this answer and someone noticed me that maybe it was wrong. 我发布这个答案已经很久了,有人注意到我可能是错的。 I really don't know why the OP marked my answer as the right one (maybe OP was looking for this rather than c++-cli syntax? Who knows now) .
我真的不知道为什么OP标记我的答案是正确的(也许OP正在寻找这个而不是c ++ - cli语法?现在谁知道) 。
Anyway, in c++-cli it would be: 无论如何,在c ++ - cli中它将是:
someObj->SomeEvent+= gcnew EventHandler(this, &Blah_SomeEvent);
The syntax for C++/CLI is : C ++ / CLI的语法是:
delegate void MyOwnEventHandler(Object^ sender, Eventargs^ e)
{
}
to register this for an event: 为此活动注册:
objectPtr->MyEvent += gcnew EventHandler(MyOwnEventHandler);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.