Using EventHandler in C++/CLI

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-11 01:49:43

问题


-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


回答1:


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;




回答2:


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.




回答3:


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>.



来源:https://stackoverflow.com/questions/9699740/using-eventhandler-in-c-cli

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!