我们已获得使用C#开发购物车的任务 哪个有项目(属性:名称,价格) ItemOrder(属性:项目,数量) 我试图找出一个产品的净价格作为价格*数量,但价格属性总是返回0,我甚至尝试打印该名称,它似乎为null 数量显示正常。
班级项目
private string name;
private double price;
public string Name { get { return name; } set { name=value;} }
public double Price { get { return price; } set { price = value; } }
public Item()
{
Name = this.name;
Price = this.price;
}
public Item(string name, double price)
{
Name = name;
Price = price;
}
Class ItemOrder:Item
private Item product;
private int quantity {get; set;}
public int Quantity { get {return quantity ;} set { quantity=value ;} }
public ItemOrder()
{
this.product.Name = Name;
this.product.Price = Price;
this.Quantity = Quantity;
}
public ItemOrder(Item product, int quantity)
{
this.product=product;
Quantity = quantity;
}
主要方法: ItemOrders在购物车中正确添加并打印,但我无法访问价格和计算名称
List<Item> inventory = new List<Item>();
Item pancakes = new Item("Pancakes", 6.25);
inventory.Add(pancakes);
List<ItemOrder> currentCart = new List<ItemOrder>();
ItemOrder item = new ItemOrder(inventory[userInput], quantity);
currentCart.Add(item);
foreach (ItemOrder i in currentCart)
{
double currentPrice = 0;
currentPrice = (i.Price*.i.Quantity);
Console.WriteLine("(" + (currentCart.IndexOf(i) + 1) + ") : " + i.ToString() + "\t "+currentPrice);
}
提前致谢
答案 0 :(得分:4)
由于这一行:
ItemOrder item = new ItemOrder(inventory[userInput], quantity);
您正在调用此构造函数:
public ItemOrder(Item product, int quantity)
{
this.product = product;
Quantity = quantity;
}
所以您要查找的价格实际上在product
变量中。
尝试将Product
添加为公共财产:
public Item Product { get {return product;} set { product=value ;} }
并替换此行:
currentPrice = (i.Price*.i.Quantity);
用这个:
currentPrice = (i.Product.Price * i.Quantity);
答案 1 :(得分:4)
这里有很多问题。
{ get; set; }
。(i.Price*.i.Quantity)
不对。您需要以某种方式访问Price
内product
的{{1}},而ItemOrder
应该只是*.
*
引用的product
的最简单方法是创建公共属性。 ItemOrder
,而不是简单地拨打Name
(将返回ToString()
)。例如:
Item
这将打印
public class Item {
public string Name { get; set; }
public double Price { get; set; }
public Item()
{
}
public Item(string name, double price)
{
this.Name = name;
this.Price = price;
}
}
public class ItemOrder
{
public Item Product { get; set; }
public int Quantity { get; set; }
public ItemOrder()
{
}
public ItemOrder(Item product, int quantity)
{
this.Product = product;
this.Quantity = quantity;
}
}
void Main()
{
List<Item> inventory = new List<Item>();
Item pancakes = new Item("Pancakes", 6.25);
inventory.Add(pancakes);
List<ItemOrder> currentCart = new List<ItemOrder>();
ItemOrder item = new ItemOrder(inventory[0], 2); // stand in values for userInput and quantity
currentCart.Add(item);
foreach (ItemOrder i in currentCart)
{
double currentPrice = i.Product.Price*i.Quantity;
Console.WriteLine("(" + (currentCart.IndexOf(i) + 1) + ") : " + i.Product.Name + "\t " + currentPrice);
}
}