为什么以下C#代码在可空的DateTime初始化时抛出NullReferenceException?

Mik*_*nen 3 c# nullable nullreferenceexception

这是一些简单的代码:

    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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

问题是,为什么以下步骤使其与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:
Run Code Online (Sandbox Code Playgroud)

Mar*_*ell 10

这是在声明捕获的变量范围的上下文中移动执行点的副作用.将其报告为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();
}
Run Code Online (Sandbox Code Playgroud)

在哪里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;
    }
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是当您将执行位置拖动到:

DateTime? date = new DateTime();
Run Code Online (Sandbox Code Playgroud)

你是实际上(在IL方面)将其拖动到行:

ctx.date = new DateTime();
Run Code Online (Sandbox Code Playgroud)

紧接着之前的捕获上下文行,即

var ctx = new SomeCaptureContext();
Run Code Online (Sandbox Code Playgroud)

从来没有得到执行,因此ctxnull.因此NullReferenceException.

将此作为一个错误记录是合理的,但它是一个微妙的 - 你不一定总是想要拖动执行上下文来初始化捕获上下文 - 它必须是"如果它们是null".