Home > 未分类 > Compile Error C3918 , for event in Cli/C++

Compile Error C3918 , for event in Cli/C++

In C#, we can check if an event variable is null before firing the event. For example:

public class MyClass
{
  public event EventHandler MyEvent;
  public void FireEvent()
  {
    // Check if there is any event handler registered.
    if (MyEvent != null) { MyEvent(this, new EventArgs()); }
  }
}

But if we do the same thing in C++/CLI, we will get an compile error C3918.

ref class MyClass
{
public:
  event EventHandler^ MyEvent;
  void FireEvent()
  {
    if(MyEvent != nullptr) // C3918
    {
      MyEvent(this, gcnew EventArgs());
    }
  }
};

Here is the solution:

public ref class MyClass
{
  EventHandler^ m_myEvent;
public:
  event EventHandler^ MyEvent
  {
    void add(EventHandler^ handler) { m_myEvent += handler; }
    void remove(EventHandler^ handler) { m_myEvent -= handler; }
    void raise(Object^ sender, EventArgs^ e)
    {
      // Check if there is any event handler registered.
      if (m_myEvent != nullptr)
      {
        m_myEvent->Invoke(sender, e);
      }
    }
  }
};

Categories: 未分类
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment