操作'?“不能适用于类型“串”和“System.DBNull'的操作数操作、适用于、类型、DBNull

2023-09-03 15:53:09 作者:ら醉枫染墨。

我有以下的C#code:

I have the following C# code:

sqlCommand.Parameters.AddWithValue("@Parameter", table.Value ?? DBNull.Value);

但它引发以下编译错误:

But it throws the following compilation error:

操作 ?? 不能应用于类型的操作数字符串 System.DBNull

Operator ?? cannot be applied to operands of type string and System.DBNull

为什么没有编译器允许这种语法?

Why doesn't the compiler allow this syntax?

推荐答案

两个操作数需对象。使用显式类型转换:

Both operands need to be object. Use explicit cast:

(object)table.Value ?? DBNull.Value;