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”有可能為空,這樣會出一個錯誤:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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");

妙。

posted @   Bruce_Cheung  阅读(749)  评论(0编辑  收藏  举报
编辑推荐:
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示