订阅事件的 C++/CLI 语法是什么?
我正在使用如下行更新一些旧的托管 C++ 代码:
instanceOfEventSource->add_OnMyEvent(
new EventSource::MyEventHandlerDelegate(this, MyEventHandlerMethod) );
其中
- EventSource 是发布事件的类
- instanceOfEventSource 是该类的实例
- EventSource::MyEventHandlerDelegate 是事件的委托类型
- MyEventHandlerMethod 是当前类(其中“this”是一个实例)中的一个(非静态)方法,其签名与 EventSource::MyEventHandlerDelegate
匹配在 C++/CLI 中正确的语法是什么?
I'm updating some old Managed C++ code with lines like this:
instanceOfEventSource->add_OnMyEvent(
new EventSource::MyEventHandlerDelegate(this, MyEventHandlerMethod) );
where
- EventSource is the class that publishes events
- instanceOfEventSource is an instance of that class
- EventSource::MyEventHandlerDelegate is the delegate type for the event
- MyEventHandlerMethod is a (non-static) method within the current class (of which "this" is an instance) with the signature matching EventSource::MyEventHandlerDelegate
What is the right syntax for this in C++/CLI?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
语法与 C# 类似,换句话说,
+=
被重载以使这成为可能:类似地用于删除。 然而,与 C# 不同的是,您不能省略事件处理程序委托的显式实例化,因此这会产生相当冗长的代码。
The syntax is similar to C#'s, in other words,
+=
is overloaded to make this possible:Analogously for removal. Unlike C#, however, you may not omit the explicit instantiation of the event handler delegate so this produces quite long-winded code.
我只是花了半个小时试图弄清楚如何将静态方法注册为事件的回调方法。 虽然OP没有特别要求注册静态方法,但这将对面临同样问题的其他人有所帮助。 实际上非常简单,在这种情况下,委托构造函数只为静态目标方法采用一个参数。
例子:
I just spent half an hour trying to figure out how to register a static method as callback method for an event. While the OP did not specifically ask for registering static methods, this will be helpful to others facing the same problem. It's actually very simple, in that case the delegate constructor takes just one parameter for the static target method.
Example: