Skip to main content
 首页 » 编程设计

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

2024年02月13日1298°冷暖

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 或更大。