我将从存储过程返回结果并将它们传递给函数以进行进一步处理.在某些情况下,其中一个字段(日期值)可能(并且非常精细)返回null.
但是,每当我将null传递给函数时,都会抛出异常,尝试将null转换为函数参数的类型.处理这个问题的最佳方法是什么?
数据:
Name StartDate EndDate
Bob 01/01/2013 NULL
Run Code Online (Sandbox Code Playgroud)
调用功能:
MyFunction(
DataRow.Item("StartDate"),
DataRow.Item("EndDate")) ' <--- invalid cast exception
Run Code Online (Sandbox Code Playgroud)
功能:
Public Function MyFunction(
ByVal StartDate as Date,
ByVal EndDate as Date) As Object
....
Return something
End Function
Run Code Online (Sandbox Code Playgroud)
编辑:很多很棒的提示,但仍然没有骰子.
将函数中的DateTime类型声明为可为空ByVal EndDate as DateTime?,结果为System.InvalidCastException: Specified cast is not valid.
使用DataRow.Field(Of DateTime)("EndDate")以及将参数声明为可空类型会导致 System.InvalidCastException: Cannot cast DBNull.Value to type 'System.DateTime'
EDIT2:找到了我的一个问题的来源.我使用的是Iif(),其中一个值是System.DBNull类型,另一个是Date类型.并且真假部分必须是相同的类型.我花了一段时间才发现这一点.
ByVal EndDate AS Nullable(Of DateTime)
Run Code Online (Sandbox Code Playgroud)
完整示例:
Public Function MyFunction(ByVal StartDate as Date, ByVal EndDate as Nullable(Of DateTime)) As Object
....
Return something
End Function
Run Code Online (Sandbox Code Playgroud)