【发布时间】:2015-07-27 04:25:11
【问题描述】:
直接取自即时窗口:
reader["DateDue"] as DateTime? 产生:
'reader["DateDue"] as DateTime?' threw an exception of type 'System.NullReferenceException'
Data: {System.Collections.ListDictionaryInternal}
HResult: -2147467261
HelpLink: null
InnerException: null
Message: "Object reference not set to an instance of an object."
Source: null
StackTrace: null
TargetSite: null
(DateTime?)reader["DateDue"] 产生:
{1/26/2015 12:00:00 AM}
Date: {1/26/2015 12:00:00 AM}
Day: 26
DayOfWeek: Monday
DayOfYear: 26
Hour: 0
Kind: Unspecified
Millisecond: 0
Minute: 0
Month: 1
Second: 0
Ticks: 635578272000000000
TimeOfDay: {System.TimeSpan}
Year: 2015
作为参考,reader["DateDue"] 产生:
{1/26/2015 12:00:00 AM}
Date: {1/26/2015 12:00:00 AM}
Day: 26
DayOfWeek: Monday
DayOfYear: 26
Hour: 0
Kind: Unspecified
Millisecond: 0
Minute: 0
Month: 1
Second: 0
Ticks: 635578272000000000
TimeOfDay: {00:00:00}
Year: 2015
这是一个错误吗?如果直接投射到 DateTime? 有效,那么使用 as DateTime? 投射也应该有效。
我确实找到了解决此问题的方法,方法是使用 没关系,它不能很好地处理空值。无论如何,有无数种方法可以解决这个奇怪的问题。reader.GetDateTime(reader.GetOrdinal("DateDue")) as DateTime?。
可以在此处找到演示该问题的 Repo:https://github.com/jjoedouglas/exceptionAsDatetime
【问题讨论】:
-
这是一个非常简单的
IDataReader在一个紧密的循环中。一点也不有趣,如果您曾经编写过使用SqlConnection和SqlCommand的代码,那么您已经看过一百万次了。 -
@MushinNoShin “这是一个非常简单的 IDataReader,处于紧密循环中”。除了你的“非常简单的循环”给出了一个没有意义的错误。向我们展示代码,不要只说使用
as关键字会引发空引用异常。 -
我可以一直使用 VS2015 重现这一点,在 VS2013 中正确打印 null。仅在即时窗口中,两者都可以正常执行。
-
我想知道这是否与 this question 有关 - 引用答案:“为了支持 lambda 表达式,我们必须在 Visual Studio 2015 中完全重写 CLR 表达式评估器。”
-
VS2015 中有一个更简单的复制,不需要项目。
(object)DBNull.Value as DateTime?随时触发。new object() as int?触发相同的 [不正确] 行为。