Koe*_*ren 3 c# datetime tostring string-formatting
我怎么能像"?"一样写Startted 是Startdate是null
public DateTime? StartDate { get; set; }
public override string ToString()
{
return String.Format("Course {0} ({1} is an {2} course, will be given by {3}, starts on {4}, costs {5:0.00} and will have maximum {6} participants"
, Name
, CourseId
, CourseType
, Teacher
, (StartDate == null ? "?" : StartDate)
, Price
, MaximumParticipants);
}
Run Code Online (Sandbox Code Playgroud)
锄头操作员的两侧需要是相同的类型.从文档:
first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换.
因此,您只需将日期转换为字符串(请注意格式由您决定):
(StartDate == null ? "?" : StartDate.Value.ToString("dd-MM-yyyy"))
Run Code Online (Sandbox Code Playgroud)
C#6允许你在没有三元运算符的情况下编写它,如下所示:
StartDate?.ToString("dd-MM-yyyy") ?? "?"
Run Code Online (Sandbox Code Playgroud)
?.
ToString
只有在StartDate
没有的情况下才会有条件地执行null
.空合并运算符??
将通过提供"?"
字符串作为null
值的替代来完成作业.
您可以进一步String.Format
使用插值字符串替换,如下所示:
return $"Course {Name} ({CourseId} is an {CourseType} course, will be given by {Teacher}, starts on {StartDate?.ToString("dd-MM-yyyy") ?? "?"}, costs {Price:0.00} and will have maximum {MaximumParticipants} participants";
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
121 次 |
最近记录: |