空Coallescing运营商 - 为什么铸造?运营商、Coallescing

2023-09-05 00:24:52 作者:更无风月

谁能告诉我,为什么做的第一下面的语句抛出一个编译错误,第二个不?

Can anyone please tell me why does the first of the following statements throws a compilation error and the second one does not?

NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, SomeString ?? DBNull.Value); // <-- Throws compilation error!
NewDatabase.AddInParameter(NewCommand, "@SomeString", DbType.String, (object)(SomeString) ?? DBNull.Value); // <-- Compiles!

我试过其他可空类型,如字节?,得到了相同的结果。谁能告诉我为什么我要投第一个对象?

I tried other nullable types such as byte? and got the same result. Can anyone please tell me why do I need to cast to object first?

推荐答案

您需要告诉使用什么类型的编译器。空合并运算符的结果类型必须是相同的操作数类型(或者第一个操作数的基本类型,如果它是一个空值类型,在某些情况下)的一个的。它不会尝试找到一个最具体的类型,两个操作数可以被转换成之类的东西。

You need to tell the compiler what type to use. The result type of the null coalescing operator has to be the same as one of the operand types (or the underlying type of the first operand, if it's a nullable value type, in some cases). It doesn't try to find a "most specific type which both operands can be converted to" or anything like that.

有关如何在语言的定义,当涉及到的空合并运算符的详细信息,请参阅C# 4语言规范,第7.13:

For the details of how the language is defined when it comes to the null coalescing operator, see the C# 4 language specification, section 7.13:

的前pression A的类型? b 取决于其隐式转换可在操作数。为了对preference中, A类型? b A0 A B ,其中 A A (前提是一个有型), B 是 B (>提供的 B