如何从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信息。
上述就是C#学习教程:如何从SqlDataReader解析Nullable分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/983307.html