如何从SqlDataReader解析Nullable

DateTime.TryParse方法将DateTime作为参数,而不是DateTime? ?

现在我有以下代码:

if(!DateTime.TryParse(reader["Placed"].ToString(), out _placed)){ throw new Exception("Order's placed datetime could not be parsed."); } 

_placed属于哪种类型

 Nullable _placed = null; 

有什么方法呢?

怎么样呢:

 int x = reader.GetOrdinal("Placed"); if(!reader.IsDBNull(x)) _placed = reader.GetDateTime(x); 

只是顶部答案和热门评论的组合。 谢谢@ Dylan-Meador和@LukeH。
(编者注:对于长尾巴,我认为这个版本可以节省大量的人力。)

 int x = reader.GetOrdinal("Placed"); DateTime? _placed = reader.IsDBNull(x) ? (DateTime?)null : reader.GetDateTime(x); 

这里@yzorg的答案变成了可重用的扩展方法

 public static class SqlDataReaderExtensions { public static DateTime? GetNullableDateTime(this SqlDataReader reader, string fieldName) { int x = reader.GetOrdinal(fieldName); return reader.IsDBNull(x) ? (DateTime?) null : reader.GetDateTime(x); } } 
 DateTime? _placed = null; DateTime d2; bool isDate = DateTime.TryParse(reader["Placed"].ToString(), out d2); if (isDate) _placed = d2; 

在尝试解析日期之前,使用阅读器的IsDBNull方法确定值是否为null。

这是正常的。 如果解析失败,则不设置out参数。 因此,如果wargument的类型是Nullable,那么它将是一个redudoant信息。