c# - “If” 条件是否比 ??和类型转换

标签 c# performance casting null-coalescing-operator

对于相同的功能,我有以下两种方法 - 一种使用“if”条件,另一种使用“??和类型转换”。哪种方法更好?为什么?

代码:

  Int16? reportID2 = null;
  //Other code

  //Approach 1
  if (reportID2 == null)
  {
       command.Parameters.AddWithValue("@report_type_code", DBNull.Value);
  }
  else
  {
     command.Parameters.AddWithValue("@report_type_code", reportID2);
  }

  //Approach 2
  command.Parameters.AddWithValue("@report_type_code", ((object) reportID2) ?? DBNull.Value);

更新

根据回答,以下是 ??

的好处
  1. 提高可读性
  2. 减少程序流的分支深度(减少圈复杂度)

注意:转换为对象的成本可以忽略不计。

引用

  1. Null-Coallescing Operator - Why Casting?

最佳答案

空合并运算符 (??) 是一种更好的方法,因为它与您的初始 block 执行相同的操作,但在一个单独的、易于阅读的行中。 这使代码更具可读性和可维护性。

这是语法糖的众多示例之一,也就是说代码语句是表示常用想法的“快捷方式”。i++ 是另一个示例,因为它替换了 我=我+ 1。它更干净、更简单,就像 ?? 一样。

关于c# - “If” 条件是否比 ??和类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13698421/

相关文章:

javascript - 这种声明的目的是什么?

java - 实现带有最终字段的接口(interface)还是直接访问字段?

android - android.graphics.BitmapFactory.nativeDecodeStream( native 方法)中的致命异常 : main java. lang.OutOfMemoryError

c++ - 使用 shared_ptr 从函数返回时进行类型转换

R float 精度在从字符转换时丢失

C# 循环遍历对象数组

PushbackInputStream 的 C# 实现

c# - 在 ASP.Net MVC 4 应用程序中使用 POCO 对象添加注释的位置

c# - WPF MarkupExtension 和 RowDefinition 导致 NotImplementedException

swift - 在 Swift 中使用协议(protocol)类型转换异常