结构体和结构体的对象在类中的位置

本文关键字:结构体 位置 对象 | 更新日期: 2023-09-27 18:17:10

我正在制作一台"自动售货机",我需要索引总销售额,以及机器中剩余的饮料数量。现在我把它设置好了,当用户点击苏打水的图片时,它会执行逻辑操作。下面是完整的类:

namespace _8_11
{
    struct Drink
    {
        public string Name;
        public float Price;
        public int Amount;
    }
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        object[,] Cola = new object[,]
        {
            {"Coke", 1.00f, 20 },
            {"Beer", 1.00f, 20 },
            {"Sprite",1.00f, 20 },
            {"Grape", 1.50f, 20 },
            {"Cream", 1.50f, 20 }
        };
        float total = 0.00f;
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Drink Coke = new Drink();
            Coke.Name = (string)Cola[0, 0];
            Coke.Price = (float)Cola[0, 1];
            Coke.Amount = (int)Cola[0, 2];
            if (Coke.Amount > 1 && Coke.Amount <= 20)
            {
                Coke.Amount -= 1;
                total += Coke.Price;
                cokeLeftLabel.Text = Coke.Amount.ToString();
                totalSalesLabel.Text = total.ToString("c");
            }
            else {
            MessageBox.Show("We are out of Coke!");
            }
        }
    }
}
主要的问题是代码:
Drink Coke = new Drink();
Coke.Name = (string)Cola[0, 0];
Coke.Price = (float)Cola[0, 1];
Coke.Amount = (int)Cola[0, 2];

当用户点击图片时,这些变量被重置。我需要在click方法之外初始化这些变量,但是当我试图将它们移到该方法之外时,它会给出一个编译错误"Coke"。数额在当前情况下不存在"。

我修复了它。下面是修改后的代码:

if (Coke.Amount > 0 && Coke.Amount <= 20)
        {
            Coke.Amount -= 1;
            Cola[0, 2] = Coke.Amount;
            total += Coke.Price;
            cokeLeftLabel.Text = Coke.Amount.ToString();
            totalSalesLabel.Text = total.ToString("c");
        }

结构体和结构体的对象在类中的位置

你可以尝试这样做:

List<Drink> drinks = new List<Drink>
{
  new Drink("Cola", 1.5f 20),
  //...
}
private void pictureBox1_Click(object sender, EventArgs e)
{
  Drink drink = drinks[0];//Get the correct drink
  drink.Amount--;
   //...      

我通常创建一个自定义图片框,如下面的代码

public class DrinkPictureBox : PictureBox
{
    Drink drink = new Drink();
    public DrinkPictureBox(string Name, float Price, int Amount)
    {
        drink.Name = Name;
        drink.Price = Price;
        drink.Amount = Amount;
    }
}

尝试将变量的声明拉入类

public partial class Form1 : Form
    {
        internal Drink Coke = new Drink();
        public Form1()
        {
            InitializeComponent();
            Coke.Name = (string)Cola[0, 0];
            Coke.Price = (float)Cola[0, 1];
            Coke.Amount = (int)Cola[0, 2];
        }
    }

然后,在Form1中声明初始约束。这应该使表单和事件都可见。我试过这样做,没有任何问题。