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

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: