写"?" 如果属性为null,则为字符串

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)

Dav*_*idG 7

锄头操作员的两侧需要是相同的类型.从文档:

first_expression和second_expression的类型必须相同,或者从一种类型到另一种类型必须存在隐式转换.

因此,您只需将日期转换为字符串(请注意格式由您决定):

(StartDate == null ? "?" : StartDate.Value.ToString("dd-MM-yyyy"))
Run Code Online (Sandbox Code Playgroud)


das*_*ght 7

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)