如何在VB.NET中将可为空的DateTime设置为null?

Pro*_*ofK 16 vb.net vb.net-2010

我正在尝试在我的UI上设置日期范围过滤器,并带有复选框,说明是否应该使用DateTimePicker的值,例如

Dim fromDate As DateTime? = If(fromDatePicker.Checked, fromDatePicker.Value, Nothing)
Run Code Online (Sandbox Code Playgroud)

然而设置fromDateNothing不会导致设置为Nothing'12:00:00 AM',并且以下If语句错误地执行过滤器,因为startDate不是Nothing.

If (Not startDate Is Nothing) Then
    list = list.Where(Function(i) i.InvDate.Value >= startDate.Value)
End If
Run Code Online (Sandbox Code Playgroud)

我如何真正确保startDate获得价值Nothing

Dam*_*ver 26

问题在于它首先检查此任务的右侧,并确定它是类型DateTime(否?).然后执行分配.

这将有效:

Dim fromDate As DateTime? = If(fromDatePicker.Checked, _
                               fromDatePicker.Value, _
                               CType(Nothing, DateTime?))
Run Code Online (Sandbox Code Playgroud)

因为它强迫右手边的类型DateTime?.

正如我在评论中所说,Nothing可能更类似于C#default(T)而不是null:

Nothing表示数据类型的默认值.默认值取决于变量是值类型还是引用类型.