从泛型函数类型的函数返回一个值

时间:2014-02-28 15:21:55

标签: vb.net function parameters type-conversion

我遇到麻烦,返回“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

1 个答案:

答案 0 :(得分:3)

如果您之前将值存储为对象,则可以:

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