【发布时间】:2014-11-19 09:02:11
【问题描述】:
我有一个“主要”表格和一个“价格”表格。 Main 类有一个 Ingredient 子类,该子类的实例在 Main 构造函数中初始化。按下按钮后,主窗体启动价格窗体。价格表单有几个文本框和一个按钮。
问题是我想通过使用价格表单中的新输入数据来修改成分子类实例的变量。我意识到可以通过构造函数参数轻松地将这些变量传递给 Price 表单,但是,我不知道如何将这些修改后的变量传递回 Main 类,因为在我将需要它们之后关闭价格表格。
主类
public partial class Main : Form
{
public class Ingredient
{
public string name;
public int weight;
public int price;
public int energy;
public int tmp;
public Ingredient(string mName, int mWeight, int mPrice, int mEnergy)
{
name = mName;
weight = mWeight;
price = mPrice;
energy = mEnergy;
}
}
public Main()
{
InitializeComponent();
Ingredient hazulnuts = new Ingredient("hazulnuts", 0, 0, 0);
}
private void bEditPrices_Click(object sender, EventArgs e)
{
// I could pass variables of the Ingredients instance here through the constructor,
// but haven't done so yet because I'm hoping there is some way that I can directly
// access variables of instances of Ingredient class as there could be quite a lot
//of these instances
Prices prices = new Prices();
prices.Show();
// The Main form is hidden when the Prices form is shown, therefore instantiating a new
//Main from the Prices isn't an option
this.Hide();
}
}
价格等级:
public partial class Prices : Form
{
public Prices()
{
InitializeComponent();
}
private void save_Click(object sender, EventArgs e)
{
// retrieve values of textboxes somehow pass the variables back to the
// Main form's Ingredient instances
//I realize that the code below is not syntactically correct but I'm looking
//for something along of the lines of that.
this.Close;
Main.show();
}
}
【问题讨论】:
-
也许当您构建价格表单
Prices prices = new Prices();时,您可以将父实例传递给子构造函数。 (例如this关键字)。然后,您将可以从子窗体访问父级的公共成员。 -
您如何存储这些信息?我假设您将此数据存储到数据库或文件或其他东西?如果是这样,您的“价格”表单应该在表单关闭时将数据保存在某处,而不是您的
Ingredient类应该只有一个名为RefreshPrices()的方法,并且该方法应该从数据库或其他任何地方加载新价格。
标签: c# winforms forms class instance-variables