不能隐式转换类型System.DateTime?到System.DateTime

Nat*_*Pet 6 c# datetime

当我做以下操作时,我得到:

    inv.RSV = pid.RSVDate
Run Code Online (Sandbox Code Playgroud)

我得到以下内容:无法隐式转换类型System.DateTime?到System.DateTime.

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

我试过以下但没有成功:

 if (pid.RSVDate != null)
 {                

    inv.RSV = pid.RSVDate != null ? pid.RSVDate : (DateTime?)null;
 }
Run Code Online (Sandbox Code Playgroud)

如果pid.RSVDate为null,我喜欢不分配inv.RSV任何东西,在这种情况下它将为null.

Ahm*_*eed 16

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

你想要做的是以下内容:

if (pid.RSVDate.HasValue)
{
    inv.RSV = pid.RSVDate.Value;
}
Run Code Online (Sandbox Code Playgroud)

或者,更简洁:

inv.RSV = pid.RSVDate ?? DateTime.MinValue;
Run Code Online (Sandbox Code Playgroud)


Tho*_*que 8

您还需要使RSV属性可以为空,或者RSVDate为null 的情况选择默认值.

inv.RSV = pid.RSVDate ?? DateTime.MinValue;
Run Code Online (Sandbox Code Playgroud)