处理这种情况的最佳方法是什么:
我有这个通用功能
Function FieldValue(Of T)(row As DataRow,fieldName As String) As T
Return If(row.IsNull(fieldName),Nothing,CType(row(fieldName),T))
End Function
在字段值为 null 且 T 为 String 的特殊情况下,我想返回 String.Empty 而不是 Nothing。
我认为最简单的方法是为 T = string 提供一个特定的函数:
Function FieldValue(row As DataRow ,fieldName As String) As String
Return If(row.IsNull(fieldName), String.Empty, CType(row(fieldName), String))
End Function
(在您现有的通用功能之上)
这是另一种选择:
Function FieldValue(Of T)(row As DataRow,fieldName As String) As T
If GetType(T) = GetType(String) And row.IsNull(fieldName) Then
Return CType(CType(String.Empty, Object), T)
Else
Return If(row.IsNull(fieldName), Nothing, CType(row(fieldName), T))
End If
End Function