简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM