微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在尝试在我的用户界面上设置一个日期范围过滤器,其复选框用于说明是否应使用DateTimePicker的值,例如
Dim fromDate As DateTime? = If(fromDatePicker.Checked,fromDatePicker.Value,nothing)

然而,将fromDate设置为nothing不会导致它被设置为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

我如何确保startDate获得nothing值?

问题是它首先检查这个赋值的右侧,并确定它是DateTime(没有?)类型.然后执行分配.

这将有效:

Dim fromDate As DateTime? = If(fromDatePicker.Checked,_
                               fromDatePicker.Value,_
                               CType(nothing,DateTime?))

因为它强制右侧的类型是DateTime?.

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

nothing represents the default value of a data type. The default value depends on whether the variable is of a value type or of a reference type.

原文地址:https://www.jb51.cc/vb/255841.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐