c# - 在下面的代码中获取空引用异常

标签 c#

public class SelectedItems
{
    public Item item;
    public int quantity;
    public double subtotal = 0.0;

}

...

Console.Write("Enter the purchased item count :");
int count = Convert.ToInt32(Console.ReadLine());

while (count > 0)
{  
    SelectedItems itm = new SelectedItems();
    Console.WriteLine("Enter the code :");
    itm.item = searchItem(Convert.ToInt32(Console.ReadLine()));

    Console.WriteLine("Enter the quantity :");
    itm.quantity = Convert.ToInt32(Console.Read());
    itm.subtotal = itm.item.unitprice * (Convert.ToDouble(itm.quantity));
}   

异常发生在最后一行。

最佳答案

最有可能的情况是您的代码搜索失败并返回空值。您应该明确检查这一点。

while (itm.item == null)
{
    Console.WriteLine("Enter the code :");
    itm.item = searchItem(Convert.ToInt32(Console.ReadLine()));
    if (itm.item == null)
    {
        Console.WriteLine("Item not found. Try again.");
    }
}

一些补充说明:

  1. 通常公共(public)领域是不受欢迎的。如果它们需要公开,最好将它们设为属性,以防您以后想要更改实现。
  2. 我认为 SelectedItems 类应该计算它自己的小计而不是在外部设置。
  3. 当您处理金钱时,您应该使用自定义 Money 类,或者至少使用 decimal 值而不是 double。使用 decimal,因为它是定点运算,通常比使用 double(或 float)更好,这样您就不用处理分数.

例子:

public class SelectedItems
{
    public Item Item { get; set; }
    public int Quantity { get; set; }
    public decimal Subtotal
    {
        get
        {
            if (Item == null)
            {
                return 0m;
            }
            return Item.UnitPrice * Quantity; /* unit price should be decimal */
        }
    }
}

您可能还想添加一些验证或业务规则检查,例如,数量必须为 0 或更大。

关于c# - 在下面的代码中获取空引用异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450359/

相关文章:

c# - Shell命名空间扩展。 C#。 C++,MFC,AT-使用什么?

c# - 如何在linq和EF中做一个简单的搜索功能

c# - 深度优先搜索永远不会达到目标状态

c# - 为什么 IPEndPoint 将 Int64 和 Int32 作为参数?

c# - unity 创建具体实例

c# - 如何使用 Windows 身份验证防止重复的 HTTP 请求

c# - 如何使用 POSTMAN 发布字符串数组?

c# - 替代私有(private)隐式转换运算符

c# - C#中以list为核心的Repository模式

c# - Azure 移动服务 Active Directory 身份验证 X-ZUMO-AUTH token 在注销后在 postman 中有效