产品售出时productSold未调用inventory.UpdateProduct的问题求助
问题排查与解决方案
嘿,我碰到过类似的问题,大概率是对象引用不统一或者方法调用的逻辑没走通,给你几个排查和解决的方向:
1. 核心问题:Inventory实例不共享
这是最常见的原因——你在ProductManagement里使用的inventory对象,和你在main里初始化的inv根本不是同一个!
举个错误的例子:
// 错误:ProductManagement内部新建了独立的Inventory实例 public class ProductManagement { private Inventory inventory = new Inventory(); // 这个和main里的inv没关系 public void productSold(Product p) { inventory.UpdateProduct(p.Id, -1); // 操作的是另一个库存,自然看不到变化 } }
解决办法:通过构造函数注入把main里的inv实例传递给ProductManagement,确保两者用的是同一个对象:
public class ProductManagement { private readonly Inventory _inventory; // 构造函数接收外部传入的Inventory实例 public ProductManagement(Inventory inventory) { _inventory = inventory; } public void productSold(Product p) { _inventory.UpdateProduct(p.Id, -1); // 现在操作的是main里的那个库存了 } } // main中的初始化代码也要对应修改 var inv = new Inventory(); var productManager = new ProductManagement(inv); // 把inv传进去 productManager.productSold(p1);
2. 检查productSold方法的内部逻辑
有没有可能在productSold里,因为某些条件判断导致UpdateProduct根本没被执行?比如:
public void productSold(Product p) { if (p == null || p.Stock <= 0) { return; // 如果p1是null或者库存为0,直接跳过更新 } inventory.UpdateProduct(p.Id, -1); }
你可以在断点处检查p1的状态,确认是否满足执行UpdateProduct的条件,或者根据业务逻辑调整这些判断。
3. 核对UpdateProduct的参数是否正确
对比一下productSold里传递给UpdateProduct的参数,和你在main里手动调用时的参数是否一致:
- 比如item id是不是
p1的正确ID? - 数量是不是负数(用来减少库存)?
如果参数不匹配,也会导致库存看起来没更新。
按照这几个方向排查,应该就能解决自动触发库存更新的问题了!
内容的提问来源于stack exchange,提问作者J. Doe
相关产品推荐
相关产品推荐

