VB   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了VB.NET通用函数大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想要做的是,根据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)

大佬总结

以上是大佬教程为你收集整理的VB.NET通用函数全部内容,希望文章能够帮你解决VB.NET通用函数所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。