开发者

CLI/C++ Virtual EventHandler

开发者 https://www.devze.com 2023-04-01 23:19 出处:网络
I have a class A which implements a interface I. In interface I is the declaration: virtual event System::EventHandler ^eh;

I have a class A which implements a interface I.

In interface I is the declaration:

virtual event System::EventHandler ^eh;

In header file of A I implement this by a similare declaration:

virtual event System::EventHandler ^eh;

in the cpp file of A I want to assign the delegate of the event to anotheter variable:

EventHandler ^eh2 = eh;

This gives error

Error 285 error C3918: usage requires 'eh' to be a data

I also try

EventHandler^ eh2 = gcnew System::EventHandler(eh);
开发者_如何学运维

This gives error:

Error 285 error C3924: error in argument #1 of delegate constructor call 'System::EventHandler':


The event keyword explicitly forbids accessing an event like this. The only valid operations are adding a handler (+= operator), removing one (-= operator) and raising the event. If you want access to the underlying delegate object then you have to provide the add and remove accessors to wrap the delegate object instead of using the default ones that the compiler generates. Like this:

public interface class IFoo {
    event EventHandler^ eh;
};

ref class Bar : IFoo {
private:
    EventHandler^ dlg;
public:
    event EventHandler^ eh {
        virtual void add(EventHandler^ handler) { dlg += handler; }
        virtual void remove(EventHandler^ handler) { dlg -= handler; }
    };
public:
    void test() {
        EventHandler^ copy = dlg;
        // etc.., fire for example
        copy(this, EventArgs::Empty);
    }
};

Do consider if this is really what you want to do, it is fairly unlikely to be correct.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号