0

我是 C++/CLI 开发的学习者,最近我遇到了关于事件处理程序的问题。

问题是:我想在继承 System::Windows::Form 的 winForm 类中添加一个自定义事件,并且该事件必须检查本机收集(如 std::deque)。每当队列的大小改变时,事件就会做一些事情。

我已经尝试在 MSDN 上找到解决方案,但我能找到的只是我不需要的自定义托管 ref 类。

4

1 回答 1

0

From your question I assume that your native collection lies somewhere in native code (a library, namespace which uses only native c++...) otherwise I'd assume that you are working with this collection completely in .Net-Environment and then I'd like to ask you why not using one of the .net collections?

If my assumption is right and the collection lies in native code than I don't know how you could achieve this communication directly. I'm programming in C++/CLI for a while now and didn't see a way how to create an "event" in native code where .Net code reacts to.

But I would suggest to use the observer-pattern or something similar which works almost as an event. To not mix native and .Net code all over your project I recommend to make a special observer class (your observer) which can be used by native code (your subject) without bringing in .Net code. It also knows the .Net Code (your winForm) and does the communication between both. This observer gets notfied by the subject(s) in your native code when the collection size changes and then calls the method in your winForm.

Additional Information for the interaction native c++ <-> c++/CLI (see comments below):

Because it isn't a simple thing to store a .Net reference in native code I recommended the extra observer class to encapsulate the interaction. In your case this means not to try to implement the winform directly as a observer class. With the additional native observer class between your subject class and the winForm you can easily register the observer and you have the problem storing a managed reference only in this class. You have 2 options:

  1. Implement the singleton pattern for your winForm to get a reference to your living instance of the Form. References can be stored temporarily as asual with Type^. You could use this to get the reference in the notify-method.

  2. Implement the native observer class and store the reference from the beginning by using gcroot. In this case you maybe have to do some casts.

In both cases you then call at the notify method a public method of the winForm which does with the collection whatever has to be done. Also the references to the .Net Framework have to be setup for the project including this observer class (should already be done when all classes lie in the same project as the winForm).

于 2013-09-09T08:10:45.387 回答