Return a value from function of the type of a generic function

守給你的承諾、 提交于 2019-12-12 05:06:42

问题


I'm having troubles returning a value of type "T". It's easier to show than to explain so here is the method:

Protected Function GetElementValue(Of T)(ByVal nodeName As String, Optional missingIfNotExists As Boolean = True,
                                                        Optional missingIfEmpty As Boolean = True,
                                                        Optional ByRef defaultVal As T = Nothing,
                                                        Optional maxLength As Integer = Nothing) As T

    'Set up the node to get the value from
    Dim node = xmlRoot.SelectSingleNode(nodeName)

    Select Case True

        Case IsNothing(node)                'If the node is missing from the xml document

            'Add the node to the misssing elements array if missingIfNotExists = True
            If missingIfNotExists Then missingElements.Add(nodeName)

            'Return the default value
            Return defaultVal

        Case node.InnerText.Trim.Length = 0 'The node exists in the xml document but has no value

            'Add it to missing elements if missingIfEmpty = True
            If missingIfEmpty Then missingElements.Add(nodeName)

            'If there is a default value passed in, return that value
            Return defaultVal

        Case Else                           'The node exists and contains data

    End Select

    'The element exists and contains data
    Dim nodeValue = node.InnerText.Trim

    'If a size constraint was passed in, ensure the element data is not too long. Shorten the string if it is
    If Not IsNothing(maxLength) AndAlso nodeValue.Length > maxLength Then nodeValue = nodeValue.Substring(0, maxLength)

    Return CType(nodeValue, T)

End Function

Any idea's or suggestions?

Thanks.

The last return is where I am having problems. It says "nodeValue cannot be converted to type T"

I have tried the below scenario and i get the error: "Value of type integer cannot be coverted to type T":

Select Case defaultVal.GetType()
    Case GetType(Integer)
        Return CType(nodeValue, Integer)
End Select

回答1:


If you store the value as an object before, it works:

Sub Main()
    Dim myInt = Foo(Of Integer)("123")
End Sub

Function Foo(Of T)(input As String) As T
    Dim bar As Object = input
    Return CType(bar, T)
End Function


来源:https://stackoverflow.com/questions/22099054/return-a-value-from-function-of-the-type-of-a-generic-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!