VB.NET - Nullable DateTime and Ternary Operator

ぐ巨炮叔叔 提交于 2019-11-27 03:26:48

问题


I'm having problems with a Nullable DateTime in VB.NET (VS 2010).

Method 1

If String.IsNullOrEmpty(LastCalibrationDateTextBox.Text) Then
    gauge.LastCalibrationDate = Nothing
Else
    gauge.LastCalibrationDate = DateTime.Parse(LastCalibrationDateTextBox.Text)
End If

Method 2

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), Nothing, DateTime.Parse(LastCalibrationDateTextBox.Text))

When given an empty string Method 1 assigns a Null (Nothing) value to gauge.LastCalibrationDate but Method 2 assigns it the DateTime.MinValue.

In other places in my code I have:

LastCalibrationDate = If(IsDBNull(dr("LastCalibrationDate")), Nothing, dr("LastCalibrationDate"))

This correctly assigns Null (Nothing) from a Ternary Operator to a Nullable DateTime.

What am I missing? Thanks!


回答1:


I will admit that I'm not an expert on this, but apparently it stems from two things:

  1. The If ternary operator can return only one type, in this case a date type, not a nullable date type
  2. The VB.Net Nothing value is not actually null but is equivalent to the default value of the specified type, in this case a date, not a nullable date. Hence the date minimum value.

I derived most of the information for this answer from this SO post: Ternary operator VB vs C#: why resolves to integer and not integer?

Hope this helps and that someone like Joel Coehoorn can shed more light on the subject.




回答2:


Bob Mc is correct. Pay extra attention to his second point - this isn't the case in C#.

What you need to do is force Nothing to a nullable DateTime by casting it as follows:

gauge.LastCalibrationDate = If(String.IsNullOrEmpty(LastCalibrationDateTextBox.Text), CType(Nothing, DateTime?), DateTime.Parse(LastCalibrationDateTextBox.Text))

Here is a snippet to demonstrate:

Dim myDate As DateTime?
' try with the empty string, then try with DateTime.Now.ToString '
Dim input = ""
myDate = If(String.IsNullOrEmpty(input), CType(Nothing, DateTime?), DateTime.Parse(input))
Console.WriteLine(myDate)

Instead of casting you can also declare a new nullable: New Nullable(Of DateTime) or New DateTime?(). The latter format looks a little odd but it's valid.



来源:https://stackoverflow.com/questions/4189876/vb-net-nullable-datetime-and-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!