我有两个类,ShoppingBasket和OrderItem,然后是Form1类。我在OrderBtem中有四个属性,我想在ShoppingBasket中使用,我该怎么做?
我有ProductName的textBox1,Quantity的numericUpDown1和LatestPrice的textBox2。按下“添加”按钮后,我将把它们添加到listBox1中。为此,我需要以某种方式使用OrderItem类中的属性; ProductName,Quantity,LatestPrice和TotalOrder(数量x LatestPrice)。然后我需要在ShoppingBasket类中的方法AddProduct中使用这些属性。
非常感谢任何帮助。
Form1中:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void addButton_Click(object sender, EventArgs e)
{
ShoppingBasket addButtonShoppingBasket = new ShoppingBasket();
addButtonShoppingBasket.AddProduct(textBox1.Text, Convert.ToDecimal(textBox2.Text), Convert.ToInt32(numericUpDown1.Value));
}
}
购物篮:
public class ShoppingBasket
{
public ShoppingBasket()
{
}
public void AddProduct(string productName, decimal latestProductValue, int quantity)
{
}
}
OrderItem的:
public class OrderItem
{
public OrderItem(string productName, decimal latestPrice, int quantity)
{
ProductName = productName;
LatestPrice = latestPrice;
Quantity = quantity;
TotalOrder = latestPrice * quantity;
}
public string ProductName { get; set; }
public decimal LatestPrice { get; set; }
public int Quantity { get; set; }
public decimal TotalOrder { get; set; }
}
答案 0 :(得分:2)
首先,您应该在OrderItem
中为ShoppingBasket
添加容器。比如Lis<OrderItem> products
,然后是
public void AddProduct(string productName,
decimal latestProductValue,
int quantity)
{
products.Add(new OrderItem(productName, latestProductValue, quantity));
}
访问OrderItem
的属性,只需撰写OrderItem.Quantity = 3
并且更好地创建Add
方法,它将接受OrderItem
:
public void AddProduct(OrderItem sb)
{
}
有关您的OrderItem
,TotalOrder
属性的内容应该是只读的(只有get
方法):
public decimal TotalOrder { get; }