简体   繁体   中英

Using EventHandler in C++/CLI

-I am trying to use event handler in c++/cli to throw event and then subscribe it in c#

class Mclass
{
 event System::EventHandler ^ someEvent;
 void ShowMessage(System::String ^)
 {
  someEvent(this,message);
 }
}

-but it throws error

error C2664: 'managed::Mclass::someEvent::raise' : cannot convert parameter 2 from 'System::String ^' to 'System::EventArgs ^'

How to rectify it

The EventHandler delegate type requires an object of type EventArgs as the 2nd argument, not a string. A quick way to solve your problem is to declare your own delegate type:

public:
    delegate void SomeEventHandler(String^ message);
    event SomeEventHandler^ someEvent;

But that's not the .NET way. That starts by deriving your own little helper class derived from EventArgs to store any custom event arguments:

public ref class MyEventArgs : EventArgs {
    String^ message;
public:
    MyEventArgs(String^ arg) {
        message = arg;
    }
    property String^ Message {
        String^ get() { return message; }
    }
};

Which you then use like this:

public ref class Class1
{
public:
    event EventHandler<MyEventArgs^>^ someEvent;

    void ShowMessage(System::String^ message) {
        someEvent(this, gcnew MyEventArgs(message));
    }
};

Note the use of the generic EventHandler<> type instead of the original non-generic one. It is more code than the simple approach but it is very friendly on the client code programmer, he'll instantly know how to use your event since it follows the standard pattern.

As winSharp93 points out, the signature for System::EventHandler takes a System::EventArgs . You can either:

  1. Create your own EventArgs -derived class that contains the string message you want,

  2. Use your own delegate instead of `System::EventHandler':

    delegate void MyDelegate(string^); event MyDelegate^ someEvent;

You can't pass a String to an EventHandler as the second parameter.

Instead, try:

someEvent(this, System::EventArgs::Empty)

If you need to pass custom data, you can create a subclass of EventArgs and use System::EventHandler<TEventArgs> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM