小编egn*_*tor的帖子

?? 或 .GetValueOrDefault()

我有属性类型int?并且decimal?正在计算中使用。如果其中任何一个的值为 null,则必须默认为 0。我试图在使用 null-coalescing 或GetValueOrDefault()如果值为 时也默认为 0 之间做出决定null。哪种方法在可读性和性能方面更好(如果有任何明显的差异)?

第一的:

public decimal MyMethod(int memberId)
{ 
    var dto = GetDtoValue(memberId);
 return (dto.PropertyOne ?? 0)
      + (dto.PropertyTwo ?? 0)
      + (dto.PropertyThree ?? 0)
      - (dto.PropertyFour ?? 0)
      + ...
}
Run Code Online (Sandbox Code Playgroud)

第二:

public decimal MyMethod(int memberId)
    { 
        var dto = GetDtoValue(memberId);
     return dto.PropertyOne.GetValueOrDefault())
          + dto.PropertyTwo.GetValueOrDefault())
          + dto.PropertyThree.GetValueOrDefault())
          - dto.PropertyFour.GetValueOrDefault())
          + ...
    }
Run Code Online (Sandbox Code Playgroud)

.net c# operators null-coalescing

7
推荐指数
1
解决办法
3976
查看次数

标签 统计

.net ×1

c# ×1

null-coalescing ×1

operators ×1