是否有可能合并在C#字符串的DBNull? [英] Is it possible to coalesce string and DBNull in C#?
问题描述
我正在写一个C#程序调用存储过程。在我传入的参数列表,它是可能的值中的一个可以合法地为空。所以我想我会用这样一行:
I'm writing a C# routine to call a stored proc. In the parameter list I'm passing in, it is possible that one of the values can legally be null. So I thought I'd use a line like this:
cmd.Parameters.Add(new SqlParameter("@theParam", theParam ?? DBNull.Value));
不幸的是,这将返回以下错误:
Unfortunately, this returns the following error:
CS0019:操作'??'不能应用于类型为'字符串'和'System.DBNull
CS0019: Operator '??' cannot be applied to operands of type 'string' and 'System.DBNull'
现在,这似乎不够清楚,但我不明白它背后的基本原理。为什么会这样不行? (通常,当我不明白为什么有什么不工作,这不是它的无法的工作......这就是我做错了。)
Now, this seems clear enough, but I don't understand the rationale behind it. Why would this not work? (And often, when I don't understand why something isn't working, it's not that it can't work...it's that I'm doing it wrong.)
难道我真的要舒展了这一点成为一个较长的if-then语句
Do I really have to stretch this out into a longer if-then statement?
编辑: (顺便说一句,这些建议只使用零作为是,这是行不通的。我本来想出空会自动翻译成DBNull的太多,但它显然并非如此。(谁知道?))
(As an aside, to those suggesting to just use "null" as is, it doesn't work. I originally figured null would auto-translated into DBNull too, but it apparently does not. (Who knew?))
推荐答案
不是那样的,没有。该类型必须匹配。这同样适用于三元如此。
Not like that, no. The types have to match. The same is true for the ternary.
现在,通过匹配,我不是说他们必须是相同的。但他们必须分配兼容。基本上:在相同的继承树
Now, by "match", I don't mean they have to be the same. But they do have to be assignment compatible. Basically: in the same inheritance tree.
要解决这个问题的方法之一是投你的字符串对象:
One way to get around this is to cast your string to object:
var result = (object)stringVar ?? DBNull.Value;
但我不喜欢这样,因为这意味着你更多地依赖于SqlParameter的构造函数让你的类型的权利。相反,我喜欢做这样的:
But I don't like this, because it means you're relying more on the SqlParameter constructor to get your types right. Instead, I like to do it like this:
cmd.Parameters.Add("@theParam", SqlDbTypes.VarChar, 50).Value = theParam;
// ... assign other parameters as well, don't worry about nulls yet
// all parameters assigned: check for any nulls
foreach (var p in cmd.Parameters)
{
if (p.Value == null) p.Value = DBNull.Value;
}
还请注意,我明确声明的参数类型。
Note also that I explicitly declared the parameter type.
这篇关于是否有可能合并在C#字符串的DBNull?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!