写 ”?”如果 属性 为空,则在字符串中

Write "?" in a string if a property is null

如何将 Startedate 写成 "?"开始日期为空

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);
}

ternery operator 的两边必须是同一类型。来自文档:

Either the type of first_expression and second_expression must be the same, or an implicit conversion must exist from one type to the other.

因此您可以简单地将日期转换为字符串(注意格式由您决定):

(StartDate == null ? "?" : StartDate.Value.ToString("dd-MM-yyyy"))

您可以调整现有代码

(StartDate == null ? "?" : StartDate.ToString())

或杠杆Nullable<T>.HasValue

(StartDate.HasValue ? StartDate.ToString() : "?")

重点是,?: 两个条件都需要相同的类型。

C# 6 允许您在没有三元运算符的情况下编写此代码,如下所示:

StartDate?.ToString("dd-MM-yyyy") ?? "?"    
只有当 StartDate 不是 null 时,

?. 才会有条件地执行 ToString。空合并运算符 ?? 将通过提供 "?" 字符串作为 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";

您可以使用 IsNullOrEmpty() 函数,它将覆盖 null 或空日期 (IsNullOrEmpty(StartDate) ? "?" : StartDate.ToString("dd-MM-yyyy"))