2011-12-05 45 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; 
相關問題