在另一种方法中调用方法

时间:2018-03-25 13:48:23

标签: c# .net

当产品销售时,我的预期行为是ProductManagement中的productSold,以调用inventory.UpdateProduct()并动态更新库存。

我已经应用了一些断点,并且在调用p.productSold(p1)时发现它实际上从未进入inventory.UpdateProduct(),因此库存永远不会更新。

为了解决这个问题,我在main 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);
    }
}

1 个答案:

答案 0 :(得分:2)

“ProductManagement”中的“库存”与您在主要功能中的库存不同。

您可以对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();
}