我正在编写一个C#例程来调用存储过程.在我传入的参数列表中,其中一个值可能合法地为空.所以我以为我会使用这样的一行:
cmd.Parameters.Add(new SqlParameter("@theParam", theParam ?? DBNull.Value));
Run Code Online (Sandbox Code Playgroud)
不幸的是,这会返回以下错误:
CS0019:运营商'??' 不能应用于'string'和'System.DBNull'类型的操作数
现在,这似乎已经足够清楚,但我不明白其背后的基本原理.为什么这不起作用?(通常情况下,当我不明白为什么某些东西不能正常工作时,并不是它无法正常工作......而是我做错了.)
我是否真的需要将其延伸到更长的if-then声明中?
编辑:(顺便说一句,对那些建议只使用"null"的人,它不起作用.我原来认为null也会自动翻译成DBNull,但它显然没有.(谁知道?))
我已将Class Person属性Birthday定义为可为空的DateTime?,那么为什么空融合运算符不应该在以下示例中起作用?
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
我得到的编译器错误是"操作员'??' 不能应用于'System.DateTime?'类型的操作数 和'System.DBNull'"
以下也出现了编译错误:
cmd.Parameters.Add(new SqlParameter("@Birthday",
SqlDbType.SmallDateTime)).Value =
(person.Birthday == null) ? person.Birthday:DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
我按照Refactor的建议添加了一个强制转换为(对象),然后编译,但是没有正常工作,并且在两种情况下,值都存储在sqlserver db中为null.
SqlDbType.SmallDateTime)).Value =
person.Birthday ?? (object)DBNull.Value;
Run Code Online (Sandbox Code Playgroud)
有人能解释一下这里发生了什么吗?
我需要使用以下笨拙的代码:
if (person.Birthday == null)
cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value
= DBNull.Value;
else cmd.Parameters.Add("@Birthday", SqlDbType.SmallDateTime).Value =
person.Birthday;
Run Code Online (Sandbox Code Playgroud)