下面是一些简单的代码:
static void Main(string[] args)
{
var coll = new List<string> {"test", "test2", "test3"};
var filteredColl = coll.Select(x => x).ToList();
if (!filteredColl.Any())
{
DateTime? date = new DateTime();
filteredColl = coll.Where(x => date.GetValueOrDefault().Date.ToString(CultureInfo.InvariantCulture) == x).Select(x => x).ToList();
}
}
问题是,为什么以下步骤会导致NullReferenceException崩溃:
1)在if处设置断点
2)设置下一个执行点:
3)尝试使用F10继续执行:
如果我注释掉代码的最后一行,它就不会崩溃。
更新:以下是堆栈跟踪:
System.NullReferenceException was unhandled HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=ConsoleApplication28 StackTrace:
at ConsoleApplication28.Program.Main(String[] args) in Program.cs: line 21
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart() InnerException:
if(..)
,你必须手动设置下一行。看到new Datetime()
部分,MaxValue
和MinValue
有错误 - 无法解引用表达式。指针无效。如果你从if(..)
中删除not
,它就可以正常运行,将该行放在if(..)
块之外也可以。 - iabbott