从泛型类型的函数返回值 [英] Return a value from function of the type of a generic function

查看:146
本文介绍了从泛型类型的函数返回值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在返回类型"T"的值时遇到麻烦.显示起来比解释要容易,所以这里是方法:

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

有任何想法或建议吗?

谢谢.

最后的回报是我遇到问题的地方.它说"nodeValue不能转换为类型T"

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

我尝试了以下情况,但出现错误:整数类型的值无法覆盖为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

这篇关于从泛型类型的函数返回值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆