如何在 VB.NET 中将可为 null 的 DateTime 设置为 null? [英] How do I set a nullable DateTime to null in VB.NET?

查看:44
本文介绍了如何在 VB.NET 中将可为 null 的 DateTime 设置为 null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to set up a date range filter on my UI, with checkboxes to say whether a DateTimePicker's value should be used, e.g.

Dim fromDate As DateTime? = If(fromDatePicker.Checked, fromDatePicker.Value, Nothing)

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

Yet setting fromDate to Nothing doesn't result in it being set to Nothing but to '12:00:00 AM', and the following If statement incorrectly executes the filter because startDate is not Nothing.

If (Not startDate Is Nothing) Then
    list = list.Where(Function(i) i.InvDate.Value >= startDate.Value)
End If

我如何才能真正确保 startDate 获得 Nothing 的值?

How do I really ensure startDate gets a value of Nothing?

推荐答案

问题在于它首先检查此作业的右侧,并确定它属于 DateTime 类型(没有<代码>?).然后执行任务.

The issue is that it's examining the right-hand side of this assignment first, and deciding that it is of type DateTime (no ?). Then performing the assignment.

这会起作用:

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

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

Because it forces the right-hand side's type to be DateTime?.

正如我在评论中所说,没什么 可以更类似于 C# 的 default(T) 而不是 null:

As I said in my comment, Nothing can be more akin to C#'s default(T) rather than null:

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

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.

这篇关于如何在 VB.NET 中将可为 null 的 DateTime 设置为 null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆