如何定义扩展以重载“+”运算符以执行简单的数组连接

How to define an extension to overload the "+" Operator for performing simple array joining

请问我们如何重载“+”运算符以方便简单的数组连接?

我们如何定义一个扩展来简化如下:

    Dim a = {1, 2}
    Dim b = {3, 4}
    Dim c = a + b ' should give {1, 2, 3, 4}

我收到以下错误:

'Error BC30452  Operator '+' is not defined for types 'Integer()' and 'Integer()'

Overloading the + operator to add two arrays 的副本。

因此,由于这是不可能的(除了使用扩展),您可以使用 LINQ 使用这个简单的解决方法:

Dim c = a.Concat(b).ToArray()

这里有一个可能的扩展实现,它使用数组和列表作为输入,并且比 LINQ 方法更有效:

<System.Runtime.CompilerServices.Extension()> _
Public Function Plus(Of t)(items1 As IList(Of T), items2 As IList(Of T)) As T()
    Dim resultArray(items1.Count + items2.Count - 1) As t
    For i As Int32 = 0 To items1.Count - 1
        resultArray(i) = items1(i)
    Next
    For i As Int32 = 0 To items2.Count - 1
        resultArray(i + items1.Count) = items2(i)
    Next
    Return resultArray
End Function

你可以这样使用:

Dim a = {1, 2}
Dim b = {3, 4}
Dim c = a.Plus(b)