【问题标题】:Where to place functional code in WinForms app在 WinForms 应用程序中放置功能代码的位置
【发布时间】:2010-10-14 16:44:36
【问题描述】:

我是 C# 新手,我正在使用 VS08,我创建了一个表单,但我应该将我的功能代码放在哪里?

现在我有 2 个文件:
程序.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}

form1.cs - 包含我的表单。

【问题讨论】:

    标签: c# winforms


    【解决方案1】:

    Winforms 的理想设计模式是 Model View Presenter。

    Martin Fowler http://martinfowler.com/eaaDev/ModelViewPresenter.html 将其分为两种变体

    【讨论】:

      【解决方案2】:

      如果您对Separation of Concerns 感兴趣,您可能希望将property inject or constructor inject 您的功能类添加到表单中,而不是将其与您的功能类紧密耦合。

      请参阅Dependency injection 了解一般注入

      【讨论】:

        【解决方案3】:

        我建议您在放置所有功能代码时创建一个新类。在 form1.cs 中使用此类的一个实例(适当地重命名)。

        【讨论】:

          【解决方案4】:

          您的代码应该包含在构成您的域功能的类中。 Program.cs 会创建一个表单实例(建议您将 form1 重命名为更具描述性的名称),然后您的表单应该实例化它需要的类。

          如果您使用数据绑定,请将一个或多个绑定源添加到您的表单,设置它们的数据源并在表单加载期间绑定。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-08-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多