我正在学习将 MVP 应用到 C# 中的简单 WinForms 应用程序(只有一种形式),并且在 static void Main()
中创建主要演示者时遇到了问题。从 Presenter 公开一个 View 以便将其作为参数提供给 Application.Run() 是个好主意吗?
目前,我已经实现了一种方法,它允许我不将 View 公开为 Presenter 的属性:
static void Main()
{
IView view = new View();
Model model = new Model();
Presenter presenter = new Presenter(view, model);
presenter.Start();
Application.Run();
}
Presenter 中的 Start 和 Stop 方法:
public void Start()
{
view.Start();
}
public void Stop()
{
view.Stop();
}
View(Windows 窗体)中的 Start 和 Stop 方法:
public void Start()
{
this.Show();
}
public void Stop()
{
// only way to close a message loop called
// via Application.Run(); without a Form parameter
Application.Exit();
}
Application.Exit() 调用似乎是关闭表单(和应用程序)的一种不优雅的方式。另一种选择是将 View 公开为 Presenter 的公共(public)属性,以便使用 Form 参数调用 Application.Run()。
static void Main()
{
IView view = new View();
Model model = new Model();
Presenter presenter = new Presenter(view, model);
Application.Run(presenter.View);
}
Presenter 中的 Start 和 Stop 方法保持不变。添加了一个附加属性以将 View 作为表单返回:
public void Start()
{
view.Start();
}
public void Stop()
{
view.Stop();
}
// New property to return view as a Form for Application.Run(Form form);
public System.Windows.Form View
{
get { return view as Form(); }
}
View(Windows 窗体)中的 Start 和 Stop 方法将编写如下:
public void Start()
{
this.Show();
}
public void Stop()
{
this.Close();
}
谁能建议哪种方法更好,为什么?或者有更好的方法来解决这个问题?
最佳答案
以下情况如何:
// view
public void StartApplication() // implements IView.StartApplication
{
Application.Run((Form)this);
}
// presenter
public void StartApplication()
{
view.StartApplication();
}
// main
static void Main()
{
IView view = new View();
Model model = new Model();
Presenter presenter = new Presenter(view, model);
presenter.StartApplication();
}
这样,您就不需要将 View 暴露给外部。此外, View 和演示者都知道此 View 已作为“主窗体”启动,这可能是一条有用的信息。
关于c# - 应如何为 MVP WinForms 应用程序的主要演示者调用 Application.Run()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2757441/