这是一些简单的代码:
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:
这是将执行点移到声明已捕获变量作用域的上下文中的副作用。将其报告为IDE错误是合理的,但修复起来并不容易。基本上,date
它不是变量-由于存在lambda,因此它是捕获上下文中的一个字段。编译器本质上会:
if (!filteredColl.Any())
{
var ctx = new SomeCaptureContext(); // <== invented by the compiler
ctx.date = new DateTime();
filteredColl = coll.Where(ctx.SomePredicate).Select(x => x).ToList();
}
在哪里SomePredicate
:
class SomeCaptureContext {
public DateTime? date; // yes, a public field - needs to support 'ref' etc
public bool SomePredicate(string x) // the actual name is horrible
{
return this.date.GetValueOrDefault()
.Date.ToString(CultureInfo.InvariantCulture) == x;
}
}
这里的问题是,当您将执行位置拖动到以下位置时:
DateTime? date = new DateTime();
您实际上(按IL术语)将其拖到行中:
ctx.date = new DateTime();
紧接其前的捕获上下文行,即
var ctx = new SomeCaptureContext();
从来没有执行过,所以ctx
也没有执行null
。因此NullReferenceException
。
将其记录为错误是合理的,但它是一个微妙的错误-并且您不一定总是希望拖动执行上下文来初始化捕获上下文-它必须是“如果它们是null
”。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句