gpt4 book ai didi

c#-4.0 - 使用三元运算符的缺点

转载 作者:行者123 更新时间:2023-12-03 06:43:59 24 4
gpt4 key购买 nike

我的源代码中有以下语句

int tableField1;
int tableField2;

int propertyField1;
int propertyField2;

if (tableField1 != null)
{
propertyField1 = tableField1;
}

if (tableField2 != null)
{
propertyField2 = tableField1;
}

// the above pattern is repeated for 10 tablefields ie tableField3, tableField4... tableField10

我使用三元运算符将上述语句简化如下

propertyField1 = tableField1 != null ? tableField1 : propertyField1;
propertyField2 = tableField2 != null ? tableField2 : propertyField2;

以下是我的问题:

1)三元运算符的使用效率是否比 if 语句低。

2)使用三元运算符有哪些缺点(如果有)。

最佳答案

为什么不使用空合并运算符呢?

propertyField1 = tableField1 ?? propertyField1;

诚然,将原始值分配回同一个变量看起来有点奇怪。它可能会比 if 语句效率稍低,因为理论上您正在读取该值并再次分配它......但如果 JIT 被省略,我不会感到惊讶那。不管怎样,这绝对是微观优化的水平。

有些人认为条件运算符不利于可读性 - 我通常认为对于像这样的简单语句来说这是很好的,尽管它在某种程度上模糊了“只有在我们已经改变值的情况下才改变值”的含义。得到了一个新的”。

关于c#-4.0 - 使用三元运算符的缺点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4149530/

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