【问题标题】:Pass information within Forms在表单中传递信息
【发布时间】:2016-01-17 15:44:10
【问题描述】:

这更像是一个理论问题,但我想知道在表单中传递信息的最佳方式是什么。我会解释我的问题:

我有我的 Mainform 类来管理整个应用程序:

public class Mainform : Form
{
        private static AddressBook _addressbook = new AddressBook();
        private static TemplateManager _templateManager = new TemplateManager();
        /*...*/
}

此外,我还有另一个由Mainform 创建的类:

public partial class TemplateLists : Form
{
        //To be filled with Mainform's information.
        private List<Template> _genericTemplates;
        private Client _clientToFill;

        //In this case, I decided to pass the information through the constructor.
        public TemplateLists(List<Template> genericTemplates, Client client)
        {
            InitializeComponent();
            _genericTemplates = genericTemplates;
            _clientToFill = client;
        }
}

问题是,为了让TemplateLists 接收_genericTemplates 信息,我不知道最好是通过构造函数、方法还是公共属性来完成,为什么。无论如何,我都知道如何实现它们,但我不知道哪个是最好的,我没有任何理由选择一个而不是另一个。

【问题讨论】:

    标签: c# forms winforms


    【解决方案1】:

    最好使用依赖注入或服务定位。检查this 和this 以供参考。

    【讨论】:

    • 为什么我应该使用模式而不是简单的解决方案,比如通过构造函数传递值?
    • @JavierGarcíaManzano 这完全取决于它提供的灵活性和模块化。使用 DI,您只需定义一次,并说明您是否希望它是单例的。而且您不必再次手动设置。
    【解决方案2】:

    没有“最好”的解决方案。这实际上归结为表格的使用方式。例如,它取决于通用模板是什么。如果它们是创建表单所必需的,最好通过构造函数传递它,以防止表单实例化不完整。

    如果它们是可选的,您可以在创建表单后分配。

    实现细节(依赖注入、具体耦合等)取决于表单的使用方式。

    【讨论】:

      【解决方案3】:

      基本上,您的整个问题可以归结为何时应该使用构造函数 (ctor) 参数与属性。

      构造函数参数:
      这些应该用于在您的实例上设置 强制 值。换句话说,这些值是您的类实例无法运行的值。

      类属性:
      当这些值对于您的对象的功能是可选的时,应该使用这些值。

      考虑一个示例,其中您的类通过服务(反过来与数据库等对话)提取数据。您还打算执行某种日志记录。在这种情况下,您知道如果没有服务实例,您的类将无法工作,但您的日志记录对于此类来说是可选的。因此,在实例化 StoreManager 时,您可以根据需要选择设置记录器。

      public class StoreManager
      {
          private readonly IService dataService;
      
          public StoreManager(IService dataService) 
          {
              if(dataService == null)
              {
                  // Do not allow to go further.
                  throw new ArgumentException();
              }
      
              this.dataService = dataService;
          }
      
          public ILogger Logger
          {
              get;
              set;
          }
      
          public IList<Product> GetProducts()
          {
              var products = dataService.GetProducts();
      
              // logging is optional
              if(Logger != null) {
                  Logger.Trace("Products fetched {0}", products.Count);
              }
          }
      }
      

      【讨论】:

      • 好吧,就这么解释了。在某些时候,我读到使用构造函数不是一个好主意,因为它们是由 VS 或类似的东西“自动生成”的,所以我很困惑。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多