在变量c#中列出名称
本文关键字:变量 | 更新日期: 2023-09-27 18:28:31
正如你在编程中看到的那样,我是一个新手,我正在做一个简单的程序练习。例如,我想把Item.price&Listbox2中的Item.Name。
是否可以将arrayName放入变量中,并将其放入foreach循环中?只是为了防止很长的IF环路或开关,或while环路。
For example :
Array variable = Drinks;
foreach(Product item in VARIABLE)
{
listBox2.Items.Add(item.ProductName + item.Price);
}
Ps:我已经尝试过一个临时列表,你把drinkList放在临时列表中,然后称之为产品。名称和/或产品价格
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; }
}
}
我不确定你到底在寻找什么,但也许你可以把产品类型(饮料或面包)放在结构中?
public struct Products
{
public string type;
public string name;
public double price;
}
然后您可以创建列表
List<Products>
并在foreach循环中使用它,就像在示例
听起来你想要的是:
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);
}
}