C# 管理类间数据的最佳方法是什么?
使用c#-WinForms,.net Framework 4.5,VS 2012 尝试创建具有某些实体的小应用程序。 我为我的实体创建单独的类,并在其中放入一些简单的代码:C# 管理类间数据的最佳方法是什么?,c#,.net,winforms,forms,list,C#,.net,Winforms,Forms,List,使用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的样本(可以通过单击
public class Car
{
public string Color {get; set;}
public string Make { get; set; }
public string CarModel { get; set; }
}
然后,我从主窗体创建了一些类Car
的样本(可以通过单击主窗体中的按钮进行创建,单击带有3个文本框的新窗体后将打开,如果输入信息并单击按钮Ok,则必须创建新Car
示例并返回主窗体)
为此,我尝试使用下一个代码:
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
字段
我发现的另一种方法是在main表单中创建next方法
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);
}
但瓦里安也不是最好的,更喜欢
问题:将创建的实体(在本例中为
Car
,表示为myCar
)从一种形式移动到另一种形式的最佳方式是什么 对于这种GUI应用程序,我建议您遵循MVC或MVP模式。类car是模型,Windows窗体是视图,视图不包含模型的实例,视图通过controller或presenter更新
您可以找到有关MVC/MVP的更多详细信息请定义“最佳”。最具可读性?快?内存有效?可能是一个汽车存储库。查找依赖注入。意味着在“最佳”最受保护的方式和Quick下,我想说你想要一个标准的工厂模式。看*当你只想要具体类型时,也有模式。
标准工厂模式
-从未听说过这一点-需要了解如果是诚实的话-从未阅读过模式
(正如我写的abowe),但是看起来它非常有用,请学习MVP-它将使您的WinForms生活更加轻松。:)@马特-非常有趣和有用的链接
private void buttonAdd_Click(object sender, EventArgs e)
{
MainForm.myCar(textBoxColor.Text,
textBoxMake.Text,
textBoxModel.Text);
MessageBox.Show("Added");
this.Close();
}