还在学习c#并弄乱了GUI,我遇到了这个问题,我一遍又一遍地查看代码,不明白为什么我的Order类不会被实例化。 Evrything对我来说很好看。我在这里缺少一个基本概念吗?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
newOrder = new Order ();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
private void listBox_SelectedIndexChanged(object sender, EventArgs e)
{
newOrder.Entree = this.listBox.Text;
}
public class Order
{
public string[] pastryEntree = new string[] { "Baklava", "Croissant", "Blueberry Muffin" };
public decimal[] pastryPrice = new decimal[] { 3.00m, 2.50m, 1.75m };
private string entree;
private decimal entreePrice;
public Order()
{
entree = "";
entreePrice = 0;
}
public string Entree
{
get
{
return entree;
}
set
{
entree = value;
SetEntreePrice();
}
}
public decimal EntreePrice
{
get
{
return entreePrice;
}
}
public void SetEntreePrice()
{
for (int i = 0; i < pastryPrice.Length; i++)
{
if (pastryEntree[i] == entree)
{
entreePrice = pastryPrice[i];
}
}
}
}
}
}
答案 0 :(得分:0)
您尚未将newOrder
定义为Form1
类的成员,因此当您尝试实例化该变量时,该变量是未声明的。
public partial class Form1 : Form
{
Order newOrder;
....
}
答案 1 :(得分:0)
您可能想要替换它:
private void Form1_Load(object sender, EventArgs e)
{
newOrder = new Order ();
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
与
private void Form1_Load(object sender, EventArgs e)
{
for (int i = 0; i < newOrder.menuEntree.Length; i++)
{
Order newOrder = new Order ();
this.listBox.Items.Add(newOrder.menuEntree[i]);
}
}
您可能希望在for循环中声明顺序。否则所有订单都是同一个实例。