我使用VB.Net
、Visual Studio 2010
、.Net 版本4.5.50938 SP1Rel
。
当 DateTime 参数为空时,我看到传递的值是 #12:00:00 AM#
,它基本上是 DateTime.MinValue
。假设 myDateTime (为空)是我传递的 DateTime 参数,
Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), Nothing, myDateTime)
将 newDateTime 的值设置为“#12:00:00 AM#
”而不是 Nothing。我验证了 If 条件返回 true。谁能告诉我为什么 Nullable (Of DateTime) 不是 Nothing ?
此外,下面的代码有效,但没有进入 If 循环。
Dim newDateTime As Nullable(Of DateTime) = Nothing
If (Not myDateTime.Equals(DateTime.MinValue)) Then
newDateTime = myDateTime
End If
最佳答案
使用“If”运算符时,两个返回值必须具有相同类型。在本例中,If 返回 true 和 false 的 DateTime。您可以通过执行以下操作来查看这一点(它不会编译)。
If(True, 123, "aaa")
所以你并没有得到真正的Nothing。相反,只需返回一个可以为空的值。
Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), New Nullable(Of DateTime), myDateTime)
或者像阿曼说的
Dim newDateTime As Nullable(Of DateTime) = If(myDateTime.Equals(DateTime.MinValue), CType(Nothing, DateTime?), myDateTime)
更好的是,不要尝试将所有内容都放在一行上;)
关于vb.net - 日期比较 myDateTime.Equals(DateTime.MinValue) 在 VB.Net 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22994273/