ItemsBillingApp中GetTotal返回0问题及6项账单功能实现咨询
GetTotal() Always Returning 0 in ItemsBillingApp Let's work through why your GetTotal() method is stuck returning 0, even with the multiplication logic you've written. Here are the most likely issues to investigate:
1. Uninitialized or invalid values for Cost/Quantity
Your calculation relies on Convert.ToInt32(this.Cost) multiplied by this.Quantity—if either value resolves to 0, the result will always be 0:
- If
Costis an empty string,null, or a non-numeric value,Convert.ToInt32()will return 0 (for empty/null inputs) or throw an exception (for non-numeric text). Since you're seeing 0 instead of errors, odds areCostis resolving to 0. - If
Quantitystays at its defaultintvalue of 0 (because your creation methods likeCreateItemWithOneItemforget to set it to 1), the multiplication will always result in 0.
2. Calling GetTotal() on the wrong instance
It's easy to accidentally call GetTotal() on a fresh, uninitialized Item object instead of the one you built with your CreateItem*, MergeItem, or CloneItem methods. Double-check your references:
- Bad:
new Item().GetTotal()(uses default 0 values) - Good:
var myItem = CreateItemWithOneItem("15"); myItem.GetTotal();
3. Logic gaps in your item manipulation methods
Take a close look at how your six methods modify Cost and Quantity:
CreateItemWithMultipleItemsAndQuantities: Are you correctly setting the total cost and quantity for the combined item, or just adding items to a list without updating these fields?MergeItem: Does merging two items update the resulting item'sCostandQuantityto reflect the merged state?CloneItem: Are you copying the original item'sCostandQuantityvalues, or leaving them as defaults in the cloned instance?
4. Access modifier issues
Ensure that Cost and Quantity have the right access modifiers (e.g., public or with public getters/setters) so your creation/modification methods can actually update their values. If they're private and not initialized properly in the class constructor or methods, GetTotal() will only see default 0 values.
Debugging Tips
To pinpoint the issue quickly, add debug checks in your GetTotal() method:
public int GetTotal() { // Inspect these values in your debugger or console output int parsedCost = Convert.ToInt32(this.Cost); int itemQuantity = this.Quantity; Console.WriteLine($"Raw Cost: {this.Cost} (parsed to {parsedCost}), Quantity: {itemQuantity}"); return parsedCost * itemQuantity; }
This will show you exactly what values are being used in the calculation—if either is 0, you'll know exactly where to fix the initialization.
内容的提问来源于stack exchange,提问作者h d

