我有这段代码,我在 ISTM 中防御性地编码以防止分配空值:
foreach (DataRow priceAndUsageVarianceRow in _dtUsage.Rows)
{
//var pauv = new PriceAndUsageVariance
//{
// Description = priceAndUsageVarianceRow["Description"].ToString(),
// Week1Usage = Convert.ToDouble(priceAndUsageVarianceRow["Week1Usage"]),
// Week2Usage = Convert.ToDouble(priceAndUsageVarianceRow["Week2Usage"]),
// UsageVariance = Convert.ToDouble(priceAndUsageVarianceRow["UsageVariance"]),
// Week1Price = Convert.ToDecimal(priceAndUsageVarianceRow["Week1Price"]),
// Week2Price = Convert.ToDecimal(priceAndUsageVarianceRow["Week2Price"]),
// PriceVariance = Convert.ToDecimal(priceAndUsageVarianceRow["PriceVariance"]),
// PriceVariancePercentage = Convert.ToDouble(priceAndUsageVarianceRow["PriceVariancePercentage"])
//};
// Got exception with the code above; trying to prevent it with this:
var pauv = new PriceAndUsageVariance();
pauv.Description = String.Empty;
pauv.Week1Usage = 0.0;
pauv.Week2Usage = 0.0;
pauv.UsageVariance = 0.0;
pauv.Week1Price = 0.00M;
pauv.Week2Price = 0.00M;
pauv.PriceVariance = 0.00M;
pauv.PriceVariancePercentage = 0.0;
if (null != priceAndUsageVarianceRow["Description"])
{
pauv.Description = priceAndUsageVarianceRow["Description"].ToString();
}
if (null != priceAndUsageVarianceRow["Week1Usage"])
{
pauv.Week1Usage = Convert.ToDouble(priceAndUsageVarianceRow["Week1Usage"]);
}
if (null != priceAndUsageVarianceRow["Week2Usage"])
{
pauv.Week2Usage = Convert.ToDouble(priceAndUsageVarianceRow["Week2Usage"]);
}
. . .
...但我得到,“对象不能从 DBNull 转换为其他类型”在最后一次尝试分配的特定迭代中(到 pauv.Week2Usage)。
该字段确实出现在类中:
public class PriceAndUsageVariance
{
public String Description { get; set; }
public Double Week1Usage { get; set; }
public Double Week2Usage { get; set; }
public Double UsageVariance { get; set; }
public Decimal Week1Price { get; set; }
public Decimal Week2Price { get; set; }
public Decimal PriceVariance { get; set; }
public Double PriceVariancePercentage { get; set; }
}
...并且代码对于大多数记录都运行良好。
什么会导致此异常,我该如何防范?