设置一个 SqlParameter 并检查它是否为空,??对?

Setting a SqlParameter and checking if it's null, ?? vs?

最近我了解到在为 SqlParameter 设置值时可以检查值是否为空,如果为空则设置为空。这是使用空合并运算符 ??,它非常简单:

cmd.Parameters.Add(new SqlParameter("ID", ID.Text ?? (object)DBNull.Value);

现在谁能更详细地解释下一个例子?显然,它正在检查字符串以查看它是否为空,但是 ? 运算符之后的一切如何工作?另外,??? 在性能方面有什么区别?

cmd.Parameters.Add(new SqlParameter("ID", ID.Text == "" ? (object)DBNull.Value : ID.Text));

它们是两个不同的函数,一个用于空值合并,另一个用作三元函数的条件运算符。 Microsoft Developer Network 将两者解释为 follows.

Null-coalescing Operator This operator has higher precedence than the next section and lower precedence than the previous section.

x ?? y – returns x if it is non-null; otherwise, returns y.


Conditional Operator This operator has higher precedence than the next section and lower precedence than the previous section.

t ? x : y – if test t evaluates to true, then evaluate and return x; otherwise, evaluate and return y.