【问题标题】:Generic Function with Special Case for String具有字符串特殊情况的泛型函数
【发布时间】:2012-06-04 11:22:52
【问题描述】:

处理这种情况的最佳方法是什么:

我有这个通用函数

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。

【问题讨论】:

    标签: .net vb.net


    【解决方案1】:

    我认为最简单的方法是为 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
    

    【讨论】:

    • 我希望能够像以前一样继续调用该函数,即Dim fv As String = FieldValue(of String)(row,fieldName)
    • 我曾尝试返回 New T 而不是 Nothing,但结果是 'New' cannot be used on a type parameter that does not have a 'New' constraint.
    • 我在同一个通用函数中添加了另一种方法。您需要一个类型约束才能使用 New,但您会将函数的使用限制为具有匿名构造函数的类型。
    • 你的回答太棒了!干杯!
    • 为什么不直接调用 Field 扩展方法和 If 运算符? Dim s As String = If(dataRow.Field(Of String)("ColumnName"), String.Empty)
    猜你喜欢
    • 1970-01-01
    • 2015-10-21
    • 2011-04-11
    • 2012-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-10
    • 1970-01-01
    相关资源
    最近更新 更多