簡體   English   中英

從泛型類型的函數返回值

[英]Return a value from function of the type of a generic function

我在返回類型“ T”的值時遇到麻煩。 顯示起來比解釋起來容易,所以這里是方法:

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

有什么想法或建議嗎?

謝謝。

最后的回報是我遇到問題的地方。 它說“ nodeValue不能轉換為類型T”

我嘗試了以下情況,但出現錯誤:“不能將整數類型的值掩蓋為T類型”:

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

如果您以前將該值存儲為對象,則可以使用:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM