DateTime和DbNull.Value [英] DateTime and DbNull.Value

查看:209
本文介绍了DateTime和DbNull.Value的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人有一个想法,为什么这个作品:

 如果(_item.Created == DateTime.MinValue)
{
ListSqlParam.Add(新的SqlParameter(@ TransactionCreated,DBNull.Value));
}
,否则
{
ListSqlParam.Add(新的SqlParameter(@ TransactionCreated,_item.Created));
}



但不是这样的:

  ListSqlParam.Add(新的SqlParameter(@ TransactionCreated((_ item.Created == DateTime.MinValue)DBNull.Value:_item.Created))); 


解决方案

的原因是,条件运算符是一个表达式一种特定类型。这种特定类型的通过基于所述类型的算子的两个分支的表达式的编译器infered。结果,
在您的代码,这种特定类型的不能由编译器,因为<$ C $ infered C> DBNull.Value 和 _item.Created 是不同的,不相关的类型。你可以不投任何一个到另一个类型。



要使它发挥作用,施展至少一个分支到对象

 (_ item.Created == DateTime.MinValue)? (对象)DBNull.Value:_item.Created 


Does anyone have an idea why this works:

if (_item.Created == DateTime.MinValue)
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", DBNull.Value));
}
else
{
  ListSqlParam.Add(new SqlParameter("@TransactionCreated", _item.Created));
}

but not this:

ListSqlParam.Add(new SqlParameter("@TransactionCreated",((_item.Created == DateTime.MinValue) ? DBNull.Value : _item.Created)));

解决方案

The reason is that the conditional operator is an expression of a specific type. This specific type is infered by the compiler based on the types of the expressions in the two branches of the operator.
In your code, this specific type can't be infered by the compiler because DBNull.Value and _item.Created are of different and unrelated types. You can't cast either one to the type of the other one.

To make it work, cast at least one branch to object:

(_item.Created == DateTime.MinValue) ? (object)DBNull.Value : _item.Created

这篇关于DateTime和DbNull.Value的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆