You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何重构SonarQube提示存在空值路径的Lambda表达式代码?

解决SonarQube空值警告的C#代码重构方案

SonarQube的警告源于FirstOrDefault()可能返回null,直接访问其CustInternalId属性会触发空引用异常。以下是几种可行的重构方案:

方案一:先获取元素再判空(推荐)

通过先将匹配元素赋值给变量,再检查是否为空,避免直接访问null对象的属性:

public new List<CustomerModel> BuildRelationLines(PH.ParserHubApiBidResponse vendorBid)
{
    List<CustomerModel> bidRelations = base.BuildRelationLines(vendorBid);
   
    if (bidRelations != null && !string.IsNullOrEmpty(vendorBid.Custom2) && !string.IsNullOrEmpty(_appSettings.ResType))
    {
        var targetRelation = bidRelations.FirstOrDefault(x => x.Type == _appSettings.ResType);
        if (targetRelation != null)
        {
            targetRelation.CustInternalId = vendorBid.Custom2.Replace("-", ""); 
        }
    }
    return bidRelations; 
}

方案二:强制匹配并处理异常

如果业务逻辑要求必须存在匹配的元素,可使用First()替代FirstOrDefault(),同时捕获未找到元素的异常:

public new List<CustomerModel> BuildRelationLines(PH.ParserHubApiBidResponse vendorBid)
{
    List<CustomerModel> bidRelations = base.BuildRelationLines(vendorBid);
   
    if (bidRelations != null && !string.IsNullOrEmpty(vendorBid.Custom2) && !string.IsNullOrEmpty(_appSettings.ResType))
    {
        try
        {
            var targetRelation = bidRelations.First(x => x.Type == _appSettings.ResType);
            targetRelation.CustInternalId = vendorBid.Custom2.Replace("-", ""); 
        }
        catch (InvalidOperationException ex)
        {
            // 根据业务需求处理异常,比如记录日志或抛出自定义业务异常
            // Logger.LogWarning(ex, "未找到类型为{ResType}的CustomerModel", _appSettings.ResType);
        }
    }
    return bidRelations; 
}

方案三:使用空条件运算符简化代码

借助C# 6及以上的空条件运算符?.,当元素为空时自动跳过赋值操作:

public new List<CustomerModel> BuildRelationLines(PH.ParserHubApiBidResponse vendorBid)
{
    List<CustomerModel> bidRelations = base.BuildRelationLines(vendorBid);
   
    if (bidRelations != null && !string.IsNullOrEmpty(vendorBid.Custom2) && !string.IsNullOrEmpty(_appSettings.ResType))
    {
        bidRelations.FirstOrDefault(x => x.Type == _appSettings.ResType)?.CustInternalId = vendorBid.Custom2.Replace("-", ""); 
    }
    return bidRelations; 
}

方案选择建议

  • 优先使用方案一,明确处理空值场景,代码可读性高且避免潜在异常。
  • 方案二适合业务逻辑强制要求存在匹配元素的场景,需确保异常处理符合业务规则。
  • 方案三代码简洁,但未找到元素时无任何反馈,适合不强制要求赋值成功的场景。

内容的提问来源于stack exchange,提问作者Roger

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 09:42:33