C# ?. 判斷Null值

有一句代碼:

@Html.DisplayFor(modelItem => item.SellDate, "RegularDate")

RegularDate.cshtml 內容如下:

@model System.DateTime
@Model.ToString("yyyy/MM/dd")

目的是將數據庫里的 DateTime 顯示為完整日期,如 2019/08/09,時間部份舍去。

當 SellDate 不為空值時,用 "RegularDate"  這個 templateName 來 render SellDate 很方便,特別是批量應用該 templateName的情況下。

但是數據庫里“SellDate”有可能為空,這樣會出一個錯誤:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.
说明: 执行当前 Web 请求期间,出现未经处理的异常。请检查堆栈跟踪信息,以了解有关该错误以及代码中导致错误的出处的详细信息。 

异常详细信息: System.InvalidOperationException: The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.

源错误: 


行 86:             <td>
行 87:                 @**@
行 88:                 @Html.DisplayFor(modelItem => item.SellDate, "MyDate")
行 89:             </td>
行 90:             <td>

源文件: D:****Index.cshtml    行: 88 這

這樣就有點不適合了,其實有另外一種更簡便的方法:

采用 ?. 操作符,這是一個 C# 語法糖:

@(item.SellDate?.ToString("yyyy/MM/dd"))

當 item.SellDate 不為空時就執行 .ToString("yyyy/MM/dd")。

相當于

if (!item.SellDate != null)
    item.SellDate.ToString("yyyy/MM/dd");

妙。

原文地址:https://www.cnblogs.com/keepee/p/11326750.html