加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

VB.NET通用函数

发布时间:2020-12-17 00:22:00 所属栏目:大数据 来源:网络整理
导读:我想要做的是,根据T的类型做不同的操作.以下是我的问题的一个简单示例. Public Shared Function Example(Of T)() As T Dim retval As T If TypeOf retval Is String Then Dim myString As String = "Hello" retval = myString ElseIf TypeOf retval Is Integ
我想要做的是,根据T的类型做不同的操作.以下是我的问题的一个简单示例.
Public Shared Function Example(Of T)() As T
    Dim retval As T
    If TypeOf retval Is String Then
        Dim myString As String = "Hello"
        retval = myString
    ElseIf TypeOf retval Is Integer Then
        Dim myInt As Integer = 101
        retval = myInt
    End If
    Return retval
End Function

我得到错误“类型’字符串’的值’无法转换为’T’”与整数部分相同.如果我在将它们转移到一个对象之前将它们转移到retval它可以工作,但我认为这会破坏我的目的并且效率会降低.有任何想法吗?谢谢!

这可能有点晚了,但试试这个:
Public Shared Function CAnyType(Of T)(ByRef UTO As Object) As T
        Return CType(UTO,T)
    End Function


    Public Shared Function ExecuteSQLstmtScalar(Of T)(ByVal strSQL As String) As T
        Dim T_ReturnValue As T

        ' Here we have the result of a DB query ' 
        Dim obj As Object = "Value from DB query cmd.ExecuteScalar"
        Dim strReturnValue As Object = obj.ToString();



        Try
            Dim tReturnType As Type = GetType(T)

            If tReturnType Is GetType(String) Then
                Return CAnyType(Of T)(strReturnValue)
            ElseIf tReturnType Is GetType(Boolean) Then
                Dim bReturnValue As Boolean = Boolean.Parse(strReturnValue)
                Return CAnyType(Of T)(bReturnValue)
            ElseIf tReturnType Is GetType(Integer) Then
                Dim iReturnValue As Integer = Integer.Parse(strReturnValue)
                Return CAnyType(Of T)(iReturnValue)
            ElseIf tReturnType Is GetType(Long) Then
                Dim lngReturnValue As Long = Long.Parse(strReturnValue)
                Return CAnyType(Of T)(lngReturnValue)
            Else
                MsgBox("ExecuteSQLstmtScalar(Of T): This type is not yet defined.")
            End If

        Catch ex As Exception

        End Try

        Return Nothing
    End Function

(分泌物将您的通用结果转换为对象,然后从类型Object转换为模板类型T).

PS:您有责任确保您的代码可以正常使用可空类型和非可空类型,以及System.DbNull.Value.例如,当string为NULL且返回值类型为Boolean(不可为空)时.在旁注中,请注意VB Nothing不等于NULL,它等于C#的默认值(T)(例如Guid的System.Guid.Empty)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读