1

正如您在我的编程中看到的那样,我很新,我正在做一个简单的程序练习。例如,我想将 Item.price 和 Item.Name 放入 Listbox2。

是否可以将 arrayName 放入变量并将其放入 foreach 循环中?只是为了防止很长的 IF 循环或开关,或 while 循环。

For example : 
    Array variable = Drinks;
    foreach(Product item in VARIABLE)
                        {
                            listBox2.Items.Add(item.ProductName + item.Price);
                        } 

Ps:我已经尝试过使用临时列表,您将drinkList 放入临时列表中,然后将其命名为product.Name 和/或Product.price。

public partial class Form1 : Form
{
    List<Product> Drinks = new List<Product>() {new Product("Coca Cola", 1.2F), new Product("Fanta", 2.0F), new Product("Sprite", 1.5F) };
    List<Product> Bread = new List<Product>() { new Product("Brown Bread", 1.2F), new Product("White Bread", 2.0F), new Product("Some otherBread", 1.5F) };

    public Form1()
    {
        InitializeComponent();
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        listBox1.Items.Clear();

        if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
        {
            foreach (Product item in Drinks)
            {
                listBox1.Items.Add(item.ProductName);
            }
        }
        else 
        {
            foreach (Product item in Bread)
            {
                listBox1.Items.Add(item.ProductName);
            }
        }
    }

    private void listBox1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        // do something here
    }
}

public class Product
{
    private string productName;
    private float price;

    public Product(string productName, float price)
    {
        this.ProductName = productName;
        this.Price = price;
    }

    public string ProductName
    {
        get { return productName; }
        set { productName = value; }
    }

    public float Price
    {
       get { return price; }
       set { price = value; }
    }
}
4

2 回答 2

0

我不确定您到底在寻找什么,但也许您可以将产品类型(饮料或面包)放入结构中?

public struct Products
{
    public string type;
    public string name;
    public double price;
}

然后您可以创建列表

List<Products>

并在您的 foreach 循环中使用它,就像您在示例中所做的那样

于 2013-08-20T18:39:20.193 回答
0

听起来您正在寻找的是:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    listBox1.Items.Clear();

    // start with Bread and change if necessary.
    List<Product> products = Bread;

    if (comboBox1.Items.IndexOf(comboBox1.SelectedItem) == 0)
    {
        //change the value of "products"
        products = Drinks;
    }

    foreach (Product item in products)
    {
        listBox1.Items.Add(item.ProductName + item.Price);
    }

}
于 2013-08-20T18:55:44.380 回答