【发布时间】: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