You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ItemsBillingApp中GetTotal返回0问题及6项账单功能实现咨询

Troubleshooting 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 Cost is 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 are Cost is resolving to 0.
  • If Quantity stays at its default int value of 0 (because your creation methods like CreateItemWithOneItem forget 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's Cost and Quantity to reflect the merged state?
  • CloneItem: Are you copying the original item's Cost and Quantity values, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 15:42:39