如果不为空,则用 tostring 缩短 c# null 合并
shorten c# null coalescing with tostring if not null
我正在尝试从 aspx 页面中的数据库调用输出数据。
我正在检查我的 Repeater 正在检查的 DataTable 是否在当前行的 StartDate 列中有 DateTime 并以良好的格式输出日期。如果 Row 不包含 DateTime 那么它将是 DBNull.Value 并且我希望字符串只说“never”
以下有效,但很长并且调用了两次 DataTable,(虽然它在内存中,所以第二次调用可能对执行速度影响不大,但它会弄乱 aspx 页面并使代码更难执行阅读。)
<%# (((DataRow)Container.DataItem)["StartDate"] is DateTime) ? ((DateTime)((DataRow)Container.DataItem)["StartDate"]).ToString("yyyy-MM-dd h:mm t") + ".M." : "never" %>
然而,我想做的是按照以下非工作代码的行,因为它删除了对 DataTable 单元格的第二个引用:
<%# (((DataRow)Container.DataItem)["StartDate"] as DateTime).ToString("yyyy-MM-dd h:mm t") ?? "never" %>
不幸的是,空合并运算符需要在 ToString 之前 运行 因为 ToString on null 是一个错误,但是空合并运算符需要在 ToString 之后 运行 才能返回一个字符串,而不是 DateTime。
是否有 shorthand 方法可以做到这一点?好像是很常见的那种东西。
我已经为这些东西写了扩展,再也不用担心了
public string GetStringOrDefault(this DataRow r, string col, string def = "")
{
if (DBNull.Value.Equals(r[col]))
return def;
return r[col].ToString();
}
public string GetDateStringOrDefault(this DataRow r, string col, string format, string def = "")
{
if (DBNull.Value.Equals(r[col]))
return def;
return ((DateTime)r[col]).ToString(format);
}
用法
<%# ((DataRow)Container.DataItem)).GetDateStringOrDefault("StartDate", "yyyy-MM-dd h:mm t", "never") %>
我正在尝试从 aspx 页面中的数据库调用输出数据。
我正在检查我的 Repeater 正在检查的 DataTable 是否在当前行的 StartDate 列中有 DateTime 并以良好的格式输出日期。如果 Row 不包含 DateTime 那么它将是 DBNull.Value 并且我希望字符串只说“never”
以下有效,但很长并且调用了两次 DataTable,(虽然它在内存中,所以第二次调用可能对执行速度影响不大,但它会弄乱 aspx 页面并使代码更难执行阅读。)
<%# (((DataRow)Container.DataItem)["StartDate"] is DateTime) ? ((DateTime)((DataRow)Container.DataItem)["StartDate"]).ToString("yyyy-MM-dd h:mm t") + ".M." : "never" %>
然而,我想做的是按照以下非工作代码的行,因为它删除了对 DataTable 单元格的第二个引用:
<%# (((DataRow)Container.DataItem)["StartDate"] as DateTime).ToString("yyyy-MM-dd h:mm t") ?? "never" %>
不幸的是,空合并运算符需要在 ToString 之前 运行 因为 ToString on null 是一个错误,但是空合并运算符需要在 ToString 之后 运行 才能返回一个字符串,而不是 DateTime。
是否有 shorthand 方法可以做到这一点?好像是很常见的那种东西。
我已经为这些东西写了扩展,再也不用担心了
public string GetStringOrDefault(this DataRow r, string col, string def = "")
{
if (DBNull.Value.Equals(r[col]))
return def;
return r[col].ToString();
}
public string GetDateStringOrDefault(this DataRow r, string col, string format, string def = "")
{
if (DBNull.Value.Equals(r[col]))
return def;
return ((DateTime)r[col]).ToString(format);
}
用法
<%# ((DataRow)Container.DataItem)).GetDateStringOrDefault("StartDate", "yyyy-MM-dd h:mm t", "never") %>