2011-12-05 47 views
6

当我做下面我得到:不能隐式转换类型System.DateTime?为System.DateTime

inv.RSV = pid.RSVDate 

我得到以下几点:不能隐式转换类型System.DateTime的?到System.DateTime。

在这种情况下,inv.RSV是DateTime,pid.RSVDate是DateTime?

我尝试以下,但没有成功:

if (pid.RSVDate != null) 
{     

    inv.RSV = pid.RSVDate != null ? pid.RSVDate : (DateTime?)null; 
} 

如果pid.RSVDate是空的,我喜欢不分配inv.RSV任何在这种情况下,这将是空。

回答

15

DateTime不能为空。它的默认值是DateTime.MinValue

你想要做的是以下几点:

if (pid.RSVDate.HasValue) 
{ 
    inv.RSV = pid.RSVDate.Value; 
} 

或者,更简洁:

inv.RSV = pid.RSVDate ?? DateTime.MinValue; 
+0

inv.RSV为null开头。我怎么说不更新它没有价值的pid.RSVDate –

+0

@NatePet你检查'pid.RSVDate.HasValue'。如果它没有赋值,那么'HasValue'将返回'false',在这种情况下,你不会更新你的其他值。根据你的错误信息,'inv.RSV'是一个'DateTime',它不可能有一个空值。如果你想给它赋值null,改变它的类型为'DateTime?'为空。 –

+0

@NatePet,“inv.RSV为null开始”:你确定吗? DateTime **不能为空** –

8

你需要让RSV属性为空的太多,或者选择的情况下的默认值其中RSVDate为空。

inv.RSV = pid.RSVDate ?? DateTime.MinValue; 
+0

+1为空合并 –

1
如果一个被分配到一个 DateTime和一个被分配

DateTime?,你可以使用

int.RSV = pid.RSVDate.GetValueOrDefault(); 

这支持过载,使您可以指定默认值,如果DateTime的默认值并不理想。

如果pid.RSVDate是空的,我喜欢不分配inv.RSV东西在其中 情况下,这将是空。

int.RSV不会为空,因为您已经说过它是DateTime,而不是可为空的类型。如果它从未由您指定,则它将具有其类型的默认值,即DateTime.MinValue或0001年1月1日。

inv.RSV为null开头。我怎么说没有更新它存在于pid.RSVDate

没有价值再次,这根本不能,给你的财产的描述。但是,如果一般来说如果pid.RSVDate为空(并且您刚刚混淆在您的文字中),则您不想更新inv.RSV,那么您只需在作业中编写if检查。

if (pid.RSVDate != null) 
{ 
    inv.RSV = pid.RSVDate.Value; 
} 
2

因为inv.RSV不是可以为空的字段,所以它不能为NULL。初始化对象时,它是一个默认的inv。RSV为空日期时间,同样的,你会如果你说

inv.RSV = new DateTime() 

所以,如果你想inv.RSV设置为pid.RSV,如果它不为空,或者默认的日期时间价值在于它是空得,这样做:

inv.RSV = pid.RSVDate.GetValueOrDefault() 
0

pid.RSVDate有被null的可能性,而inv.RSV没有,所以才会如果RSVDatenull发生什么呢?

您需要检查,如果该值为null之前 -

if(pid.RSVDate.HasValue) 
    inv.RSV = pid.RSVDate.Value; 

但会inv.RSV的价值是什么,如果RSVDate为空?有没有总是将在这个属性的日期?如果是这样,您可以使用??运算符来分配默认值。

pid.RSV = pid.RSVDate ?? myDefaultDateTime; 
相关问题