. todictionary抛出异常nullreferenceexception

本文关键字:nullreferenceexception 抛出异常 todictionary | 更新日期: 2023-09-27 17:51:07

我有下面的代码. todictionary工作异常,抛出"Object reference not found"错误。

    var serviceOptions = serviceDurations.ToDictionary(so => so.OptionCode, StringComparer.OrdinalIgnoreCase);
var serviceLines = serivceLinePayments.Select(sl => new ServiceLine(serviceOptions[sl.option_code], Decimal.ToInt32(sl.quantity), sl.customer_paid_amount));

如果我将这段代码替换为。

var serviceOptions = serviceDurations.ToDictionary(so => so.OptionCode, StringComparer.OrdinalIgnoreCase);
//var serviceLines = serivceLinePayments.Select(sl => new ServiceLine(serviceOptions[sl.option_code], Decimal.ToInt32(sl.quantity), sl.customer_paid_amount));
List<ServiceLine> serviceLines = new List<ServiceLine>();
foreach (var item in serivceLinePayments)
{
var so = serviceOptions.FirstOrDefault(s => s.Value.OptionCode == item.option_code);
ServiceLine line = new ServiceLine( so.Value, Decimal.ToInt32(item.quantity), item.customer_paid_amount);
serviceLines.Add(line);
}

通过使用这段代码,没有异常,但无法找出是什么是这个异常的真正原因

. todictionary抛出异常nullreferenceexception

我相信你的代码行serviceDurations.ToDictionary( ...抛出空引用异常,这是明显的原因serviceDurations实例是null出于某种原因,所以异常。

您必须调试并找出为什么serviceDurations实例是空的