vb.net 相当于 String.Empty 的日期
vb.net Date equivalent to String.Empty
在我的程序中,我正在编写 class 来读取一个数据库 table 中的值,并将它们复制到另一个数据库中。
读取字符串字段时,我调用了一个函数来检查字符串值是否为 null,如果是,它 returns 一个空字符串,如果不是,它 returns 字符串。 (见下面的代码)
我还有 datetime
字段可以包含空值,如果没有类似的功能,我在尝试复制它们时会遇到运行时错误。
如果数据库行中的值为空,我是否可以使用下面的等效代码来输入空白日期?
Public Shared Function dbToString(o As Object) As String
If o Is DBNull.Value Then
Return String.Empty
Else
Return CStr(o)
End If
End Function
DateTime 是值类型,因此 'blank' 的概念不存在。您可以使用 MinValue
或 DateTime
但这可能会有问题,并且意图可能不明确。改用可为 null 的 DateTime
:
Public Shared Function dbToDate(o As Object) As DateTime?
If o Is DBNull.Value Then
Return Nothing
Else
Return Convert.ToDateTime(o)
End If
End Function
您可以轻松 return Nothing
。不需要像 string.empty.
这样的东西
固定代码:
Public Shared Function dbToString(o As Object) As String
If o Is DBNull.Value Then
Return Nothing
Else
Return CStr(o)
End If
End Function
在我的程序中,我正在编写 class 来读取一个数据库 table 中的值,并将它们复制到另一个数据库中。 读取字符串字段时,我调用了一个函数来检查字符串值是否为 null,如果是,它 returns 一个空字符串,如果不是,它 returns 字符串。 (见下面的代码)
我还有 datetime
字段可以包含空值,如果没有类似的功能,我在尝试复制它们时会遇到运行时错误。
如果数据库行中的值为空,我是否可以使用下面的等效代码来输入空白日期?
Public Shared Function dbToString(o As Object) As String
If o Is DBNull.Value Then
Return String.Empty
Else
Return CStr(o)
End If
End Function
DateTime 是值类型,因此 'blank' 的概念不存在。您可以使用 MinValue
或 DateTime
但这可能会有问题,并且意图可能不明确。改用可为 null 的 DateTime
:
Public Shared Function dbToDate(o As Object) As DateTime?
If o Is DBNull.Value Then
Return Nothing
Else
Return Convert.ToDateTime(o)
End If
End Function
您可以轻松 return Nothing
。不需要像 string.empty.
固定代码:
Public Shared Function dbToString(o As Object) As String
If o Is DBNull.Value Then
Return Nothing
Else
Return CStr(o)
End If
End Function