c# - native 类是否可以使用 .NET 事件?

标签 c# .net c++-cli

知道如何初始化指向“混合”类实例方法的 .NET 委托(delegate)吗?

我有这样的“混合”C++ 类:

class CppMixClass
{
public:
    CppMixClass(void){
        dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
    }
   ~CppMixClass(void);
   void UpdateState(System::Object^ sender, DotNetClass::StateEventArgs^ e){
       //doSmth
   }
}

DotNetClass是用C#实现的,Method declaration is OK with delegate。 此行产生错误:

dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(&UpdateHealthState);
error C2276: '&' : illegal operation on bound member function expression

有人知道问题的线索吗? 也许 CppMixClass 类不是纯 .NET (ref) 类?

当 UpdateHealthState 是静态方法时,我可以使用它,但我需要指向实例方法的指针。

我试过这样的:

dotNETclass->StateChanged += gcnew DotNetClass::ServiceStateEventHandler(this, &UpdateHealthState);

但这显然不起作用,因为这不是指向 .NET (ref) 类 (System::Object) 的指针(句柄)。

ServiceStateEventHandler 在 C# 中定义为:

public delegate void ServiceStateEventHandler(object sender, ServiceStateEventArgs e);

感谢阅读本文:)

最佳答案

我刚刚找到了这个问题的答案(当然是 N​​ishant Sivakumar,男人似乎对我所有的 C++/CLI 互操作相关问题都有答案):

http://www.codeproject.com/KB/mcpp/CppCliSupportLib.aspx?display=Print

答案位于“msclr/event.h” header 中,其中定义了 native 类中委托(delegate)的宏。

Nish 的代码如下:

class Demo5
{
msclr::auto_gcroot<FileSystemWatcher^> m_fsw;
public:
// Step (1)
// Declare the delegate map where you map
// native method to specific event handlers

BEGIN_DELEGATE_MAP(Demo5)
    EVENT_DELEGATE_ENTRY(OnRenamed, Object^, RenamedEventArgs^)
END_DELEGATE_MAP()

Demo5()
{
    m_fsw = gcnew  FileSystemWatcher("d:\\tmp");
    // Step (2)
    // Setup event handlers using MAKE_DELEGATE
    m_fsw->Renamed += MAKE_DELEGATE(RenamedEventHandler, OnRenamed);
    m_fsw->EnableRaisingEvents = true;
}
// Step (3)
// Implement the event handler method

void OnRenamed(Object^, RenamedEventArgs^ e)
{
    Console::WriteLine("{0} -> {1}",e->OldName, e->Name);
}
};

关于c# - native 类是否可以使用 .NET 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/424880/

相关文章:

c# - 带比较器的 LINQ 查询语法

.net - 如果紧随其后的是特定字符,则正则表达式会丢弃整个捕获

.net - 在 C++/Cli 中使用 `__await` 等待 TPL 任务

c# - 在 C# 对象上调用 C++/CLI delete

.net - 如何为 C++/cli 项目指定默认命名空间?

.net - .Net 框架的早期历史是什么?

c# - 如何在 C# 中使用 boolean 值

c# - 将集合项目设置为只读

c# - 在 C# 中监视包含特定字符串的 TCP 流量

c# - 将 Datagrid.SelectedItems 集合转换到 List<T>