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

前端 未结 3 968
忘掉有多难
忘掉有多难 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:51

    If your issue is that raise isn't private, then explicitly implement it like the docs say:

    http://msdn.microsoft.com/en-us/library/5f3csfsa.aspx

    In summary:

    If you just use the event keyword, you create a "trivial" event. The compiler generates add/remove/raise and the delegate member for you. The generated raise function (as the docs say) checks for nullptr. Trivial events are documented here:

    http://msdn.microsoft.com/en-us/library/4b612y2s.aspx

    If you want "more control", for example to make raise private, then you have to explicitly implement the members as shown in the link. You must explicitly declare a data member for the delegate type. Then you use the event keyword to declare the event-related members, as in the Microsoft example:

    // event keyword introduces the scope wherein I'm defining the required methods
    // "f" is my delegate type
    // "Event" is the unrealistic name of the event itself
    event f^ Event
    {
          // add is public (because the event block is public)
          // "_E" is the private delegate data member of type "f"
          void add(f ^ d) { _E += d; }
    
       // making remove private
       private:
          void remove(f ^ d) { _E -= d; }
    
       // making raise protected
       protected:
          void raise(int i)
          { 
             // check for nullptr
             if (_E)
             {
                _E->Invoke(i);
             }
          }
    }// end event block
    

    Wordy, but there it is.

    -reilly.

提交回复
热议问题