繁体   English   中英

如何在托管C ++中使用事件正确实现C#接口

[英]How to correctly implement C# interface with event in managed C++

您好,我正在尝试在托管c ++ dll中实现C#接口,如下所示:

public ref class MyClass : public IMyInterface 
{
 // Inherited via IMyInterface
 virtual event EventHandler<MyEventArgs ^> ^ MyLoadedEvent;

 public:
     virtual event EventHandler<MyEventArgs ^> MyLoadedEvent 
                {
                    void add(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                    void remove(MyEventArgs ^ f)
                    {
                      // some magic
                    }
                }
}

但是我不断收到两个错误:

1)事件类型必须是委托到委托类型

2)类无法实现在... dll中声明的接口成员函数“ MyLoadedEvent :: add”

我在实现中缺少什么,或者实现接口事件的正确方法是什么?

谢谢!

第一个错误是由于缺少^帽子引起的,第二个错误是由于未命名实现的接口方法引起的。 假设接口事件名为“ Loaded”,则正确的语法应类似于:

public ref class MyClass : IMyInterface {
    EventHandler<MyEventArgs^>^ MyLoadedEventBackingStore;
public:
    virtual event EventHandler<MyEventArgs^>^ MyLoadedEvent {
        void add(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::add {
            MyLoadedEventBackingStore += arg;
        }
        void remove(EventHandler<MyEventArgs^>^ arg) = IMyInterface::Loaded::remove {
            MyLoadedEventBackingStore -= arg;
        }
    }
};

暂无
暂无

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

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