[英]Calling a method within another method
出售產品時,我的預期行為是讓ProductManagement中的productSold調用inventory.UpdateProduct()
並動態更新庫存。
我已經應用了一些斷點,並發現在調用p.productSold(p1)時,它實際上從不輸入stock.UpdateProduct inventory.UpdateProduct()
,因此從不更新庫存。
為了解決這個問題,我已經在主inv.UpdateProduct(item id, quantity)
顯式調用了該方法,並且它似乎正在工作,但是,我希望在productSold時調用UpdateProduct。
class Program
{
static void Main(string[] args)
{
// Products
Product p1 = new Product(1, 20, 1000);
// Inventory
Inventory inv = new Inventory();
ProductManagement p = new ProductManagement();
// Add Products to inventory
inv.AddProduct(p1);
// Products sold
p.productSold(p1);
//inv.UpdateProduct(1,50);
// View Inventory
inv.ViewInventory();
Console.ReadLine();
}
}
class Product
{
public int _id;
public int _price;
public int _quantity;
public Product(int id, int price, int quantity)
{
_id = id;
_price = price;
_quantity = quantity;
}
}
class Inventory
{
private List<Product> inventory = new List<Product>();
public Inventory()
{
}
public void AddProduct(Product product)
{
inventory.Add(product);
}
public void UpdateProduct(int id, int quantity)
{
foreach(Product p in inventory)
{
if (p._id == id)
{
Console.WriteLine("product found");
p._quantity -= quantity;
}
else
{
Console.WriteLine("cannot find product");
}
}
/* var product = inventory.Single(x => x._id == id);
product._quantity -= quantity; */
}
public void ViewInventory()
{
foreach(Product p in inventory)
{
Console.WriteLine("Item ID : {0} Item Price : {1} Item Quantity : {2}", p._id, p._quantity, p._quantity);
}
}
}
class ProductManagement
{
public Inventory inventory = new Inventory();
public void productSold(Product product)
{
var quantitySold = 1;
inventory.UpdateProduct(product._id, quantitySold);
}
}
“產品管理”中的“庫存”不同於您在“主要”功能中擁有的庫存。
您可以對ProductManagement進行以下更改:(添加帶有參數的構造函數)
public class ProductManagement
{
public Inventory inventory;
public ProductManagement(Inventory inv)
{
this.inventory = inv;
}
public void productSold(Product product)
{
var quantitySold = 1;
inventory.UpdateProduct(product._id, quantitySold);
}
}
如下更改您的主:
static void Main(string[] args)
{
Product p1 = new Product(1, 20, 1000);
Inventory inv = new Inventory();
ProductManagement p = new ProductManagement(inv); //THE CHANGE
inv.AddProduct(p1);
p.productSold(p1);
inv.ViewInventory();
Console.ReadLine();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.