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

标签 c#-4.0

我的源代码中有以下语句

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/

相关文章:

c# - "this"可以在 C# 虚拟方法中为 null 吗?其余的实例方法会发生什么?

c# - 按字符串字段方法的通用排序

c#-4.0 - protobuf-net 中没有为 System.Version 定义序列化器

c# - 使用 mongoDB C# 驱动程序,如何发出 runCommand?

c# - 在范围列表中搜索数字的最快方法

javascript - 将值分配给在页面加载时从 javascript 函数获得的文本框

c# - ASP.NET MVC 3 是否缓存过滤器?

c#-4.0 - 在 NAudio 中设置音量

c# - 如何在 operator== 方法中检查 null?

c# - 在 windows 启动时设置 c# windows 应用程序