连接数组不返回字符串

时间:2014-11-29 17:33:34

标签: arrays vb.net string

我试图制作一个通用的toString方法,将char()和string()转换为字符串:

Function toString(ByVal arr As Array) As String
    If arr.GetType() Is GetType(String()) Then
        Return String.Join(".", arr)
    Else
        Return New String(arr)
    End If
End Function

加入string()会返回System.String[]而不是字符串本身。我做错了吗?

1 个答案:

答案 0 :(得分:2)

您应该使用重载来执行此操作:

Sub Main()
  Dim a() As String = {"1", "2", "3"}
  Dim c() As Char = {"a"c, "b"c, "c"c}

  Dim aString As String = ToString(a)
  Dim cString As String = ToString(c)
End Sub

Function ToString(arr() As String)
  Return String.Join(".", arr)
End Function

Function ToString(c() As Char)
  Return New String(c)
End Function

如果你 DirectCast 编辑arr到一个字符串数组,你的方法就会有用,否则编译器会选择错误的String.Join重载:

Function toString(ByVal arr As Array) As String
  If arr.GetType() Is GetType(String()) Then
    Return String.Join(".", DirectCast(arr, String()))
  Else
    Return New String(arr)
  End If
End Function

但请不要这样做。 arr.GetType() Is GetType(String())也可以只是TypeOf arr Is String()