正如您在我的编程中看到的那样,我很新,我正在做一个简单的程序练习。例如,我想将 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; }
}
}