本文介绍了是“如果”条件好过?和铸造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下的相同的功能两种方式 - 一个以如果条件和一个与??铸造哪种方法更好,为什么
代码:
的Int16 reportID2 = NULL;?
//其他代码
//方法1
如果(reportID2 == NULL)
{
命令。 Parameters.AddWithValue(@ report_type_code,DBNull.Value);
}
,否则
{
command.Parameters.AddWithValue(@ report_type_code,reportID2);
}
//方法2
command.Parameters.AddWithValue(@ report_type_code((对象)reportID2)?? DBNull.Value);
更新
根据答案,以下是 ??
- 增加可读性 $ b $的好处b
- 降低分支deapth程序流程(减少圈复杂度)
的
注:铸造作为对象是可以忽略不计的成本
参考
- 的
解决方案
我一直使用的:
command.Parameters.AddWithValue(@名 ,价值? DBNull.Value);
command.ExecuteScalar()为int? ?? -1;
等。
它增加了代码的可读性,减少分支深度。还为与数据库相关的方案,如ADO.NET尤其是创建。
I have following two approaches for same functionality - one with "if" condition and one with "?? and casting". Which approach is better? Why?
Code:
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);
UPDATE
Based on the answers, following are the benefits of ??
- Increased readability
- Decreased branching deapth of program flow (reduced cyclomatic complexity)
Note: Cost of casting as object is negligible.
REFERENCE
解决方案
I always use null-coalescing operator in such cases:
command.Parameters.AddWithValue("@name", value ?? DBNull.Value);
command.ExecuteScalar() as int? ?? -1;
etc.
It increases code readability, decreases branching depth. Also was created especially for database-related scenarios such as ADO.NET.
这篇关于是“如果”条件好过?和铸造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!