未实例化 Order 类的对象

本文关键字:对象 Order 实例化 | 更新日期: 2023-09-27 18:30:39

仍在

学习 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];
                }
            }
        }
    }
}

}

未实例化 Order 类的对象

您尚未将newOrder定义为Form1类的成员,因此当您尝试实例化变量时,该变量是未声明的。

public partial class Form1 : Form
{
    Order newOrder;
    ....
}

您可能希望替换它:

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 循环中声明顺序。否则,所有订单都将是同一实例。