gpt4 book ai didi

c# - ??或 .GetValueOrDefault()

转载 作者:行者123 更新时间:2023-12-04 02:48:04 27 4
gpt4 key购买 nike

关闭。这个问题是opinion-based .它目前不接受答案。












想改善这个问题吗?更新问题,以便可以通过 editing this post 用事实和引文回答问题.

5 天前关闭。




Improve this question




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

第一的:

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

第二:
public decimal MyMethod(int memberId)
{
var dto = GetDtoValue(memberId);
return dto.PropertyOne.GetValueOrDefault())
+ dto.PropertyTwo.GetValueOrDefault())
+ dto.PropertyThree.GetValueOrDefault())
- dto.PropertyFour.GetValueOrDefault())
+ ...
}

最佳答案

可读性
这当然是意见,但是

  • 我读了 ?? 0感觉一下子就清楚了
  • 我读了 GetValueOrDefault并且必须花一点时间考虑类型,然后是该类型的默认值(我不认为这是一个问题,只是指出“心理映射”)

  • 表现
    This article认为 GetValueOrDefault编译为技术上更快的 CIL,但改进是 micro-optimization最好。
    SharpLab但是,两个版本都编译为完全相同的 CIL(通过 Marc's comment below ),这将使它们的性能相同。
    无论哪种方式,性能差异充其量是微不足道的,在最坏的情况下不存在,这意味着 应优先考虑可读性 .

    关于c# - ??或 .GetValueOrDefault(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56437217/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com