如何在VB.NET中使用泛型?

时间:2011-08-17 13:47:46

标签: .net vb.net generics

我有以下代码:

Public Shared Function GetListAsString(ByVal data As List(Of String)) As String
    Dim retVal As String = "| "
    For Each obj As String In data
        retVal = retVal + obj.ToString() + " |"
    Next
    Return retVal
End Function

它将List转换为可打印的String。现在它已设置为使用只是列表。我觉得它应该能够使用任何类型的集合。我是Collections和generics的新手。当我尝试做类似

的事情
Public Shared Function GetListAsString(ByVal data As Collection(T)) As String
    Dim retVal As String = "| "
    For Each obj As String In data.ToString()
        retVal = retVal + obj.ToString() + " |"
    Next
    Return retVal
End Function

我收到错误。有人能指出我正确的方向吗?

5 个答案:

答案 0 :(得分:4)

您没有从编译器收到非常有用的错误消息。你忘了把功能变得通用,它不能产生像样的诊断。让我们关注更大的问题:

    For Each obj As String In data.ToString()
        retVal = retVal + obj.ToString() + " |"
    Next

For循环被破坏,从data.ToString()开始。只需使用数据。并且数据的元素类型是T,而不是String。此外,由于您只是枚举集合,您可以使用较小的接口IEnumerable<>,使其适用于更多的集合类型。因此:

Public Shared Function GetCollectionAsString(Of T)(ByVal data As IEnumerable(Of T)) As String
    Dim retVal As String = "| "
    For Each obj As T In data
        retVal = retVal + obj.ToString() + " |"
    Next
    Return retVal
End Function

请注意函数名称后添加的(Of T),即解决原始错误消息的名称。

答案 1 :(得分:3)

Collection(T)应为IEnumerable(Of T)

更新顺便说一句,顺便说一句,只要你想从集合对象中ToStringToString在课程Object和所有其他课程中定义继承Object,你可以使用

Public Shared Function GetListAsString(ByVal data As IEnumerable(Of Object)) As String

答案 2 :(得分:2)

您需要在方法签名上指定泛型。

Public Shared Function GetListAsString(Of T)(ByVal data As ICollection(Of T)) As String

编辑我改了它。

答案 3 :(得分:2)

相同的解决方案,但由于VB.Net推理的魔力,代码更少:

Public Shared Function GetListAsString(Of T)(ByVal data As IEnumerable(Of T)) As String
    Dim retVal = "| "    
    For Each obj In data
        retVal &= obj.ToString + " |"
    Next
    Return retVal
End Function

修改

或者甚至更简单地使用String.Join ......

Public Shared Function GetListAsString(Of T)(ByVal data As IEnumerable(Of T)) As String
    Return "| " & String.Join(" |", data) & " |"
End Function

答案 4 :(得分:1)

缩短版Hans's answer,使用扩展方法代替显式For Each循环:

Public Function GetListAsString(Of T)(ByVal data As IEnumerable(Of T)) As String
    Return data.Aggregate("| ", Function(d, s) d & s.ToString & " |")
End Function

但你从评论中尝试过Snowbear的建议吗?

"| " & String.Join(" | ", data) & " |"

String.Join代码确实提供了与您问题中的代码略有不同的行为,但它非常简单。这是差异

empty-sequence -> "| |" rather than "| "
1, 2 -> "| 1 | 2 |" rather than "| 1| 2 |" (was that really what you meant?)