在表单中传递信息

本文关键字:信息 表单 | 更新日期: 2023-09-27 18:18:14

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

我有我的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信息,我不知道它是否最好通过构造函数,方法或公共属性来完成,以及为什么。在任何情况下,我知道如何实现它们,但我不知道哪一个是最好的,我没有任何理由选择一个而不是另一个。

在表单中传递信息

基本上你的整个问题可以归结为什么时候应该使用构造函数(tor)参数和属性。

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

类属性

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

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

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);
        }
    }
}

最好使用依赖注入或服务位置。查看这个和这个作为参考

不存在"最好"的解决方案。这实际上取决于如何使用表单。例如,这取决于泛型模板是什么。如果它们对于创建表单是必需的,那么通过构造函数传递它是一个好主意,以防止表单实例化不完整。

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

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