C++/CLI - Event Notification

#include "stdafx.h"
#include <iostream>
 
using namespace System;
 
delegate void MyEventHandler();
 
ref class Notifier {
private:
    MyEventHandler ^ _changed;
 
public:
    event MyEventHandler ^ OnChanged {
        void add(MyEventHandler ^e) {
            _changed += e;
        }
        void remove(MyEventHandler ^e) {
            _changed -= e;
        }
    }
 
    void Update() {
        if (_changed != nullptr) {
            _changed();
        }
    }
};
 
void onchange_g() {
    std::cout << "on change (global)" << std::endl;
}
 
ref class App {
    void onchange_1() {
        std::cout << "on change 1" << std::endl;
    }
 
    void onchange_2() {
        std::cout << "on change 2" << std::endl;
    }
 
    Notifier ^ _test;
 
public:
    App() {
        _test = gcnew Notifier();
        _test->OnChanged += gcnew MyEventHandler(this, &App::onchange_1);
        _test->OnChanged += gcnew MyEventHandler(this, &App::onchange_2);
        _test->OnChanged += gcnew MyEventHandler(onchange_g);
        _test->Update();
    }
};
 
int main(array<System::String ^> ^args)
{
    auto app = gcnew App();
    return 0;
}
      
  • 输出结果
on change 1
on change 2
on change (global)
  • 简化事件的定义
#define DEFINE_EVENT(type, name)        \
    private:                            \
        type ^ _##name;                 \
    public:                             \
        event type ^ name {             \
            void add(type ^ e) {        \
                _##name += e;           \
            }                           \
            void remove(type ^ e) {     \
                _##name -= e;           \
            }                           \
        }
      
ref class Notifier {
    DEFINE_EVENT(MyEventHandler, OnChanged)
 
    void Update() {
        if (_OnChanged != nullptr) {
            _OnChanged();
        }
    }
};