【问题标题】:How to correctly implement C# interface with event in managed C++如何在托管 C++ 中正确实现带有事件的 C# 接口
【发布时间】:2018-05-20 14:16:13
【问题描述】:

您好,我正在尝试在我的托管 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”

我在实现中遗漏了什么或者实现接口事件的正确方法是什么?

谢谢!

【问题讨论】:

    标签: c# c++ visual-c++ c++-cli managed-c++


    【解决方案1】:

    第一个错误是由于缺少 ^ 帽子引起的,第二个错误是由于未命名您实现的接口方法引起的。假设接口事件被命名为“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;
            }
        }
    };
    

    【讨论】:

    • 非常感谢这为我解决了这个问题,我对连续的所有 ^ ^ 感到困惑(互联网表情符号不是双关语)
    猜你喜欢
    • 1970-01-01
    • 2013-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-26
    • 1970-01-01
    • 2021-12-29
    • 1970-01-01
    相关资源
    最近更新 更多