gpt4 book ai didi

c# - 属性始终返回零/空值

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:30 24 4
gpt4 key购买 nike

我们接到一项任务,要使用 C# 开发购物车其中有项目(属性:名称,价格)ItemOrder(属性:项目,数量)我试图找出产品的净价作为价格*数量,但价格属性总是返回 0,我什至尝试打印名称,但它显示为空不过数量显示正确。

类元素

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;
}

类 ItemOrder : 项目

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);
}

提前致谢

最佳答案

因为这一行:

ItemOrder item = new ItemOrder(inventory[userInput], quantity);

你正在调用这个构造函数:

public ItemOrder(Item product, int quantity)
{
this.product = product;
Quantity = quantity;
}

所以您要查找的价格实际上在 product 变量中。

尝试将Product 添加为公共(public)属性:

public Item Product { get {return product;} set { product=value ;} }

并替换这一行:

currentPrice = (i.Price*.i.Quantity);

用这个:

currentPrice = (i.Product.Price * i.Quantity);

关于c# - 属性始终返回零/空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21493461/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com