簡體   English   中英

不能隱式轉換類型System.DateTime? 到System.DateTime

[英]cannot implicitly convert type System.DateTime? to 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為null,我喜歡不分配inv.RSV任何東西,在這種情況下它將為null。

DateTime不能為null。 它的默認值是DateTime.MinValue

你想要做的是以下內容:

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

或者,更簡潔:

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

您還需要使RSV屬性可以為空,或者為RSVDate為空的情況選擇默認值。

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

因為inv.RSV不是可空字段,所以它不能為NULL。 當你初始化你的對象時,它是一個默認的inv.RSV到一個空的DateTime,就像你說的那樣

inv.RSV = new DateTime()

因此,如果要將inv.RSV設置為pid.RSV(如果它不是NULL),或者默認的DateTime值為null,請執行以下操作:

inv.RSV = pid.RSVDate.GetValueOrDefault()

如果被分配為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為空,你不想更新inv.RSV (並且你的語言只是混淆了),那么你只需在作業周圍寫一個if檢查。

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

pid.RSVDate有可能為null ,而inv.RSV沒有,所以如果RSVDatenull會發生什么?

你需要在之前檢查值是否為null -

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

但是如果RSVDate為空,inv.RSV的值是多少? 這家酒店總會有約會嗎? 如果是這樣,你可以使用?? 如果您願意,可以指定運算符。

pid.RSV = pid.RSVDate ?? myDefaultDateTime;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM