gpt4 book ai didi

c# - 如何在托管 C++ 中正确实现带有事件的 C# 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 01:38:32 28 4
gpt4 key购买 nike

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

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) 事件类型必须是句柄到委托(delegate)类型

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

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

谢谢!

最佳答案

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

关于c# - 如何在托管 C++ 中正确实现带有事件的 C# 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678699/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com