我想要做的是,根据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它可以工作,但我认为这会破坏我的目的并且效率会降低.有任何想法吗?谢谢!
这可能有点晚了,但试试这个:
原文链接:https://www.f2er.com/vb/255335.htmlPublic 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)