订阅事件的 C++/CLI 语法是什么?

发布于 2024-07-13 07:08:43 字数 520 浏览 12 评论 0原文

我正在使用如下行更新一些旧的托管 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

岁月打碎记忆 2024-07-20 07:08:43

语法与 C# 类似,换句话说,+= 被重载以使这成为可能:

instanceOfEventSource.MyEvent +=
    gcnew EventSource::MyEventHandlerDelegate(this, &MyClass::MyEventHandlerMethod);

类似地用于删除。 然而,与 C# 不同的是,您不能省略事件处理程序委托的显式实例化,因此这会产生相当冗长的代码。

The syntax is similar to C#'s, in other words, += is overloaded to make this possible:

instanceOfEventSource.MyEvent +=
    gcnew EventSource::MyEventHandlerDelegate(this, &MyClass::MyEventHandlerMethod);

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.

猫卆 2024-07-20 07:08:43

我只是花了半个小时试图弄清楚如何将静态方法注册为事件的回调方法。 虽然OP没有特别要求注册静态方法,但这将对面临同样问题的其他人有所帮助。 实际上非常简单,在这种情况下,委托构造函数只为静态目标方法采用一个参数。

例子:

System::EventHandler^ h = gcnew System::EventHandler(&MyClass::MyStaticCallbackMethod);

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:

System::EventHandler^ h = gcnew System::EventHandler(&MyClass::MyStaticCallbackMethod);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文