处理这种情况的最佳方法是什么:
我有这个通用功能
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。
答案 0 :(得分:2)
我认为最简单的方法是为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