0

我使用 MVP 设计模式创建 Windows 窗体应用程序。例子:

IViewInterface view = new FormSome();
IPresenter presenter = new Presenter(view);

在演示者构造函数中,我执行以下操作:

public Presenter( IViewInterface view ) {
    this.view = view;

    this.view.someEvens += myMethod;
}

现在我的问题是:当我做这样的事情时会发生什么:

IViewInterface view;
{
    view = new FormSome();
    IPresenter presenter = new Presenter(view);
}
// if my presenter exists here? 

我不想显式地调用演示者的任何方法。我只想让我的演示者处理视图的事件。GC 是从内存中删除我的 Presenter,还是 GC 知道我的 Presenter 处理视图事件,所以只要视图存在,我的 Presenter 也会存在?

编辑

我测试了它并且它有效。但我不确定它是否有效,因为 GC 还没有破坏我的演示者,或者 GC 比我想象的更聪明。

4

1 回答 1

2

演示者仍将保持“活动”状态,因为它通过此处设置的事件被引用

this.view.someEvens += myMethod;

如果视图被 GC 收集,那么 Presenter 也会被销毁。

But please note that you do not have a reference to the presenter at the moment! You can not access it anymore after the code snipped you've posted.

EDIT
This, by the way, happened to be a problem for me when I thought I had destroyed all instances of a class, but they were still active because I had accidentially used them as event targets. I had TCP commands being handled even though they shouldn't have been handled.

That's why I can tell that what you're asking is actually the case :-)

于 2012-05-21T15:07:33.723 回答