从C ++ / CLI提升事件的正确方法? [英] Proper way of raising events from C++/CLI?

查看:197
本文介绍了从C ++ / CLI提升事件的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道什么是从C ++ / CLI提升事件的正确方法。在C#的一个首先可以制作处理程序的副本,检查它是否不为空,然后调用它。 C ++ / CLI有类似的做法吗?

I was wondering what's the proper way of raising events from C++/CLI. In C# one should first make a copy of the handler, check if it's not null, and then call it. Is there a similar practice for C++/CLI?

推荐答案

C ++ / CLI允许您覆盖 raise 自定义事件 处理程序,所以您不必在 null 或在提出事件时复制。当然,在你自定义的中加注你还需要这样做。

C++/CLI allows you to override raise in custom event handlers so you don't have to test for null or copy when raising the event. Of course, inside your custom raise you still have to do this.

示例,从MSDN修改正确性:

Example, adapted from the MSDN for correctness:

public delegate void f(int);

public ref struct E {
   f ^ _E;
public:
   void handler(int i) {
      System::Console::WriteLine(i);
   }

   E() {
      _E = nullptr;
   }

   event f^ Event {
      void add(f ^ d) {
         _E += d;
      }
      void remove(f ^ d) {
        _E -= d;
      }
      void raise(int i) {
         f^ tmp = _E;
         if (tmp) {
            tmp->Invoke(i);
         }
      }
   }

   static void Go() {
      E^ pE = gcnew E;
      pE->Event += gcnew f(pE, &E::handler);
      pE->Event(17);
   }
};

int main() {
   E::Go();
}

这篇关于从C ++ / CLI提升事件的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆