从C ++ / CLI提高事件的适当方法? [英] Proper way of raising events from C++/CLI?

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

问题描述

我想知道什么是从C ++ / CLI提高事件的正确方法。在C#中,应首先创建处理程序的副本,检查它是否不为null ,然后调用。 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允许您覆盖 / code>在 自定义事件 处理程序中不得不测试 null 或在提高事件时复制。当然,在你的自定义 raise 里面你还需要这样做。

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.

例子, :

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天全站免登陆