1

我想将其转换为通用函数:

Dim NewArray As String() = {"a", "b", "c"}
MsgBox(String.Join(vbNewLine, NewArray))

这是我尝试过的:

Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    Dim IntArray As Array = {1, 2, 3}       ' Integer array
    Dim StrArray() As String = {"a", "b", "c"} ' String array

    MsgBox(Join_Array(IntArray, vbNewLine, Integer))
    MsgBox(Join_Array(StrArray, vbNewLine, String))

End Sub

Private Function Join_Array(ByVal array As Object, ByVal Separator As String, ByVal array_type As Type)
    Return String.Join(Separator, array.Cast(Of array_type))
End Function
4

1 回答 1

1

你也可以这样写:

Private Function Join_Array(ByVal array As Array, ByVal Separator As String)
    Return String.Join(Separator, array.Cast(Of Object).Select(Function(x) x.ToString))
End Function

MsgBox(Join_Array(StrArray, " ")) ' a b c
MsgBox(Join_Array(IntArray, " ")) ' 1 2 3

在这里,您依赖对象的ToString方法来执行您可能需要的任何格式设置。请注意,这实际上不是通用方法。泛型是在编译时指定的,但在这种情况下,我在运行时调用Integer类的ToString方法覆盖。

一个适当的通用函数看起来像这样

Private Function Join_Array(Of T)(ByVal array As IEnumerable(Of T), ByVal Separator As String)
    Return String.Join(Separator, array.Select(Function(x) x.ToString))
End Function

注意没有必要Cast在函数内部调用,因为类型在编译时是已知的。但是,因为IntArray它是非泛型的,所以在您的Form1_Load方法中,您必须像这样调用它:

MsgBox(Join_Array(IntArray.Cast(Of Integer), " ")) ' 1 2 3
于 2013-06-09T04:52:32.270 回答