使用声纳法分析我的代码,并被告知以下代码“在至少一个执行路径上'alloc'为空”
public RetirementAdvantageProgramSleeveAllocation(VariableDVAPolicy policy, Fund fund)
: base(policy, fund)
{
SleeveAllocation alloc = null;
if (fund.FundAccountType == FundAccountType.PortfolioChoice)
{
alloc = PortfolioChoiceAccountAllocation;
}
else if (fund.FundAccountType == FundAccountType.Heritage)
{
alloc = HeritageAccountAllocation;
}
else if (fund.FundAccountType == FundAccountType.RetirementProtection)
{
alloc = RetirementProtectionAccountAllocation;
}
alloc.PercentValue = fund.Value;
alloc.PercentAllocation = fund.Value;
alloc.Units = 0;
alloc.Value = 0;
}
alloc.PercentValue = fund.Value;
是我获取可能的System.NullReferenceException的地方,但这是否是误报?还是我真的需要将所有这些都包装成if (alloc == null)
谢谢
答案 0 :(得分:0)
您具有三个条件-一个if
和两个else if
。
如果满足这些条件中的任何一个,将为alloc
指定一个参考。
但是如果都不满足怎么办?然后,您尝试使用alloc
,但它为空。
问题是,如果这些条件都不成立,将会发生什么。您是否要引发异常,还是要为alloc
分配其他内容?
您可以在最后的else
中这样做:
else
// throw an exception or assign something else
或者您可以在末尾添加支票:
if (alloc == null)
// throw an exception or assign something else
您正在执行的操作也可能更好地表示为switch
语句,因为所有三个条件都在检查fund.FundAccountType
的值。从技术上讲,它的作用与您所做的相同,但是可以很容易地看出所有条件都基于该值。