简体   繁体   English

在C ++ / CLI中使用EventHandler

[英]Using EventHandler in C++/CLI

-I am trying to use event handler in c++/cli to throw event and then subscribe it in c# - 我试图在c ++ / cli中使用事件处理程序来抛出事件然后在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 ^' 错误C2664:'managed :: Mclass :: someEvent :: raise':无法将参数2从'System :: String ^'转换为'System :: EventArgs ^'

How to rectify it 如何纠正它

The EventHandler delegate type requires an object of type EventArgs as the 2nd argument, not a string. EventHandler委托类型需要EventArgs类型的对象作为第二个参数,而不是字符串。 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. 但这不是.NET的方式。 That starts by deriving your own little helper class derived from EventArgs to store any custom event arguments: 开始通过派生从EventArgs的派生存储任何自定义事件参数自己的小助手类:

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. 请注意使用通用的EventHandler <>类型而不是原始的非泛型类型。 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 . 正如winSharp93指出的那样, System::EventHandler的签名需要一个System::EventArgs You can either: 你可以:

  1. Create your own EventArgs -derived class that contains the string message you want, 创建您自己的EventArgs派生类,其中包含您想要的字符串消息,

  2. Use your own delegate instead of `System::EventHandler': 使用您自己的委托而不是`System :: EventHandler':

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

You can't pass a String to an EventHandler as the second parameter. 您不能将String作为第二个参数传递给EventHandler

Instead, try: 相反,尝试:

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

If you need to pass custom data, you can create a subclass of EventArgs and use System::EventHandler<TEventArgs> . 如果需要传递自定义数据,可以创建EventArgs的子类并使用System::EventHandler<TEventArgs>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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