C# 格式化日期定义
我有DateTime属性DateCreation,它不是空的。 我可以这样做:C# 格式化日期定义,c#,C#,我有DateTime属性DateCreation,它不是空的。 我可以这样做: String test=myObject.DateCreation.FormatDate(); 如果对象上的DateTime属性可为空,则如下所示: public virtual DateTime? LastInteractionDate { get; set; } 我不能这样做: String test=myObject.LastInteractionDate.FormatDate(); 错误是: 约会时间?
String test=myObject.DateCreation.FormatDate();
如果对象上的DateTime属性可为空,则如下所示:
public virtual DateTime? LastInteractionDate { get; set; }
我不能这样做:
String test=myObject.LastInteractionDate.FormatDate();
错误是:
约会时间?不包含“FormatDate”的定义
如何解决空字符串为空的问题?您可以使用
.Value
获取基础值类型:
String test = myObject.LastInteractionDate.Value.FormatDate();
并检查是否为空:
String test = myObject.LastInteractionDate != null
? myObject.LastInteractionDate.Value.FormatDate()
: string.Empty;
在这种情况下,如果
LastInteractionDate
属性为空,则结果将为空字符串。您可以使用.Value
获取基础值类型:
String test = myObject.LastInteractionDate.Value.FormatDate();
并检查是否为空:
String test = myObject.LastInteractionDate != null
? myObject.LastInteractionDate.Value.FormatDate()
: string.Empty;
在这种情况下,如果
LastInteractionDate
属性为空,则结果将为空字符串。您也可以使用HasValue
属性而不是!=null
。没错,HasValue
是检查null的替代方法。如果使用C#6-string test=myObject?.LastInteractionDate?.FormatDate()代码>谢谢大家,C#6语法很有趣,但是您能为null添加值吗?类似于:string test=myObject?.LastInteractionDate?.FormatDate():string.Empty代码>我认为变量声明足以获取类型。我不知道用“.Value”表示空值的技巧。您也可以使用HasValue
属性而不是!=null
。没错,HasValue
是检查null的替代方法。如果使用C#6-string test=myObject?.LastInteractionDate?.FormatDate()代码>谢谢大家,C#6语法很有趣,但是您能为null添加值吗?类似于:string test=myObject?.LastInteractionDate?.FormatDate():string.Empty代码>我认为变量声明足以获取类型。我不知道用“.Value”表示空值的诀窍。