Proper way of raising events from C++/CLI?

前端 未结 3 975
忘掉有多难
忘掉有多难 2020-12-31 06:09

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

3条回答
  •  轮回少年
    2020-12-31 06:52

    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.

    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();
    }
    

提交回复
热议问题