无法隐式转换类型System.DateTime?为System.DateTime。

6
当我执行以下代码时,会出现以下结果:
    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赋值给任何内容,这样它将为空。
5个回答

16

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

你想要做的是以下操作:

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

更简洁地说:

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

inv.RSV一开始就是空的。如果pid.RSVDate没有值,我该怎么说不要更新它? - Nate Pet
@NatePet 你检查 pid.RSVDate.HasValue。如果它没有被赋值,那么 HasValue 将返回 false,在这种情况下,你不需要更新其他的值。根据你的错误信息,inv.RSV 是一个 DateTime 类型,它不可能有空值。如果你想将其赋值为空,将其类型更改为 DateTime?,使其可为空。 - Ahmad Mageed
@NatePet,“inv.RSV一开始就是null”:你确定吗?DateTime 不可能为空 - Thomas Levesque

8

您需要将RSV属性也设为可为空,或者选择一个默认值,以处理RSVDate为null的情况。

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

2

因为inv.RSV不是可空字段,所以它不能为NULL。当您初始化对象时,它将默认将inv.RSV设置为一个空的DateTime,就像您说的那样。

inv.RSV = new DateTime()

所以,如果您希望在inv.RSV不为NULL时将其设置为pid.RSV,或者在它为NULL时将其设置为默认的DateTime值,请执行以下操作:

inv.RSV = pid.RSVDate.GetValueOrDefault()

1
如果被分配的变量是 DateTime 类型,而被分配的值是 DateTime? 类型,你可以使用以下代码:
int.RSV = pid.RSVDate.GetValueOrDefault();

这支持一种重载,允许您指定默认值,如果DateTime的默认值不理想。

如果pid.RSVDate为null,则我不想分配inv.RSV中的任何内容,在这种情况下它将为null。

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

inv.RSV最初为null。如果pid.RSVDate没有值,我该如何说不要更新它

根据您对属性的描述,这根本不可能。但是,如果一般而言,如果pid.RSVDate为null时您不想更新inv.RSV(并且您只是在混淆自己的话),那么您只需在赋值周围编写一个if检查即可。

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

0

pid.RSVDate 可能为 null,而 inv.RSV 不可能为 null,那么如果 RSVDatenull 会发生什么呢?

在进行操作之前,您需要检查该值是否为 null -

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

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

pid.RSV = pid.RSVDate ?? myDefaultDateTime;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接