【问题标题】:What is the best way for managing data between classes?管理类之间数据的最佳方式是什么?
【发布时间】:2013-11-20 18:20:07
【问题描述】:

使用 c# - WinForms、.net Framework 4.5、VS 2012

尝试用一些实体创建小应用程序。 我为我的实体创建了单独的类,并在里面放了一些简单的代码:

public class Car
{
    public string Color {get; set;}
    public string Make { get; set; }
    public string CarModel { get; set; }
}

然后从主窗体创建一些类Car 的样本(可以通过单击主窗体中的按钮来创建,单击带有3个文本框的新窗体后,如果输入信息并单击按钮确定-新@ 987654324@ 必须创建样本并返回主窗体。

为此,我尝试使用下一个代码:

    public Car myCar = new Car();
    private void buttonAdd_Click(object sender, EventArgs e)
    {
        myCar.Color = textBoxColor.Text;
        myCar.Make = textBoxMake.Text;
        myCar.CarModel = textBoxModel.Text;
        this.DialogResult = DialogResult.OK;
        this.Close();
        MessageBox.Show("Added");
        this.Close();
    }

为了将数据从新表单移动到主表单,我使用公共字段public Car myCar = new Car();,但这不是最好的方法,因为使用了public 字段。

我发现的另一种方法 - 在主窗体中创建下一个方法

    static List<Car> carInStock = null;
    public static void myCar(string color, string make, string model)
    {
        Car myCar = new Car
        {
            Color = color,
            CarModel = model,
            Make = make
        };
        MainForm.carInStock.Add(myNewCar);
    }

对于按钮可以使用如下方法:

    private void buttonAdd_Click(object sender, EventArgs e)
    {
        MainForm.myCar(textBoxColor.Text,
        textBoxMake.Text,
        textBoxModel.Text);
        MessageBox.Show("Added");
        this.Close();
    }

但认为瓦里安也不是最好的和首选的。

问题:将创建的实体(在本例中为Car 的实体,表示为myCar)从一种形式移动到另一种形式的最佳方法是什么?

【问题讨论】:

  • 请定义“最佳”。最易读?快的?内存效率?
  • 可能是一个汽车存储库。查找依赖注入。
  • 表示“最佳”最受保护的方式和快速
  • 我想说你想要一个标准的工厂模式见en.wikipedia.org/wiki/Factory_method_pattern *当你只想要具体类型时也有模式。
  • standard factory pattern- 从来没有听说过这个 - 需要阅读

标签: c# .net winforms forms list


【解决方案1】:

对于这种 GUI 应用程序,我建议你遵循 MVC 或 MVP 模式。 car 类是模型,Windows 窗体是视图,视图不包含模型的实例,视图通过控制器或演示者进行更新。

您可以找到有关 MVC/MVP 的更多详细信息here

【讨论】:

  • 老实说 - 从来没有读过关于 patterns 的文章(正如我在上面写的那样),但看起来它非常有用
  • 请学习 MVP - 它会让您的 WinForms 生活更轻松。 :)
  • @Matt - 非常有趣和有用的链接
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-10
相关资源
最近更新 更多