DBNull 的简要用法? (三元?)
三元运算符似乎存在某种类型混淆。我知道这个问题已在其他 SO 线程中得到解决,但它始终与可空值有关。另外,就我而言,我真的只是在寻找更好的方法。
我希望能够使用,
proc.Parameters[PARAM_ID].Value =
string.IsNullOrEmpty(dest.Id) ? DBNull.Value : dest.Id;
但我却陷入了困境:
if (string.IsNullOrEmpty(dest.Id))
{
proc.Parameters[PARAM_ID].Value = DBNull.Value;
}
else
{
proc.Parameters[PARAM_ID].Value = dest.Id;
}
三元运算符失败,因为 DBNull 和字符串之间无法进行转换,并且考虑到 Value is object 看起来很愚蠢,编译器将其踢回给我我被迫关心。这个问题的可为空版本的答案是将 null 转换为字符串并完成它;但 DBNull 不能转换为字符串,所以运气不佳。
有没有更简洁的方法来做到这一点(顺便说一下,不使用可空值?)
谢谢!
It seems that there's some type confusion in the ternary operator. I know that this has been addressed in other SO threads, but it's always been with nullables. Also, for my case I'm really just looking for a better way.
I'd like to be able to use
proc.Parameters[PARAM_ID].Value =
string.IsNullOrEmpty(dest.Id) ? DBNull.Value : dest.Id;
but instead I'm stuck with this:
if (string.IsNullOrEmpty(dest.Id))
{
proc.Parameters[PARAM_ID].Value = DBNull.Value;
}
else
{
proc.Parameters[PARAM_ID].Value = dest.Id;
}
The ternary operator fails because there's no conversion possible between DBNull and string, and as silly as that seems considering Value is object, the compiler kicks it back to me and I'm forced to care. The answer to the nullable version of this question is to just cast null to string and be done with it; DBNull can't be cast to string, though, so no luck there.
Is there a more concise way to do this (without using nullables, by the way?)
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以将第一个语句更改为:
You could change your first statement to:
或者您可以添加扩展方法,例如:
然后您可以说
(改编自 Phil Haack)
可读且简洁,不是吗?
Or you could add an extension method such as:
And then you could just say
(Adapted from Phil Haack)
Readable and concise, no?
值
属性的类型为object
,因此您应该转换为object
,而不是string
:The
Value
property is of typeobject
, so you should cast toobject
, notstring
:使用怎么样?空合并运算符 有关 ?? 的更多详细信息运算符
What about using the ?? null-coalescing operator More details about ?? operator