结构和结构的对象在哪里属于类?

时间:2016-11-08 16:36:06

标签: c# object struct

我正在制作一台自动售货机"我需要索引总销售额和机器中剩余的饮料量。现在我已经设置了当用户点击苏打水的图片时,它会做逻辑。这是完整的课程:

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];

当用户点击图片时,这些变量将被重置。我需要在clicked方法之外初始化这些变量,但是当我尝试将它们移到这个方法之外时,它会给出一个编译错误&#34; Coke.Amount在当前上下文中不存在&#34;。

我修好了。以下是修订后的代码:

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");
        }

3 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

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--;
   //...      

答案 1 :(得分:1)

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

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;
    }
}

答案 2 :(得分:1)

尝试将变量的声明拉入类

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期间声明初始约束。这应该可以看到表单和事件。我试图这样做,并没有任何问题。