使用 Me.New() 在通用 class 中设置数组上界

Setting array upperbound in a generic class using Me.New()

以下是 MSDN documentation for constructing a generic class 中给出的通用 class 示例的简化版本。为了便于参考,我已经用字母标签标记了各种语句。

Module Module1
    Sub Main()
        Dim iList As New simpleList(Of Integer)(2) 'A
    End Sub
End Module

Public Class simpleList(Of itemType)
    Private items() As itemType  'B
    Private top As Integer
    Private nextp As Integer
    Public Sub New()   ' C
        Me.New(9)   'D
    End Sub
    Public Sub New(ByVal t As Integer) 'E
        MyBase.New()     'F
        items = New itemType(t) {}  'G
        top = t
        nextp = 0
    End Sub
End Class

我不理解上面代码中的以下几点:

  1. B中我们声明了一个名为items的数组类型变量,它可以指向一个数组。但是这个变量还没有指向任何数组。这个理解对吗?

  2. A中提到的数字“2”被传递给标记为E的构造函数。在 G 中,创建了一个大小为 2(即三个元素)的整数数组,变量 items 指向这个新创建的数组。此外,当 MyBase.New () i.e. F 被执行时,它会调用无参数构造函数 C.

  3. 我不明白的是:无参数构造函数C有什么用?在文档中,提到 C 将 items 数组的上限设置为 10 个元素。我的问题是:

    i) Me.New(9)D如何设置上限?我只是不明白 Me.New 是如何仅引用数组并设置其最大大小的。因为 ME 应该引用包含数组项和其他元素的当前实例 iList!!

    ii) 要设置上限,我们不能简单地将 B 重写为: Private items(9) as itemType??

这是错误的:

Also when MyBase.New () i.e. F gets executed it calls the parameterless constructor C.

该线路正在呼叫 MyBase.New(),而不是 Me.New()。它不是调用相同 class 的无参数构造函数,而是调用基础 class,即 Object.

基本上,如果您使用参数调用构造函数,那么您将创建一个具有该上限的数组,如果您调用无参数构造函数,那么它会调用另一个上限为 9 的构造函数。实际上,您可以指定一个上限,如果你不这样做,它默认为 9。