当变量定义大小时,为什么索引超出范围?

时间:2014-05-14 00:24:17

标签: arrays vb.net properties

当我使用变量定义整数数组的大小时,我得到错误:“IndexOutOfRangeException未处理”。但是,如果我只使用与我使用的变量相同的值,它就可以工作。

我将在下面的评论中解释它:

Public Class Form1

    Dim test As Test

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        test = New Test(5) 'the length property is test is 5
        test.AddToList()
    End Sub

End Class
Public Class Test

    Dim _length As Integer
    Public Property length() As Integer
        Get
            Return _length
        End Get
        Set(ByVal value As Integer)
            _length = value
        End Set
    End Property

    Dim _magnitude(length, 2) As Integer 'Size is length, which should be equal to 5. If I remove length and just put 5, it works fine.
    Public Property magnitude As Integer(,)
        Get
            Return _magnitude
        End Get
        Set(ByVal value As Integer(,))
            _magnitude = value
        End Set
    End Property

    Public Sub New(ByVal lengthp As Integer)
        length = lengthp 'Sets 5 to the length property.
    End Sub

    Public Sub AddToList()
        magnitude(4, 0) = 4 'Operates on the magnitude property. This is where the error is located.
        Debug.Print(magnitude(4, 0))
    End Sub

End Class

希望你们明白我在问什么。

2 个答案:

答案 0 :(得分:3)

在构造函数之前初始化私有字段。实例化类时,_magnitudelength设置之前初始化,因此您获得的等价于Dim _magnitude(0, 2) As Integer

尝试将声明更改为:

Dim _magnitude(,) As Integer
'...
Public Sub New(ByVal lengthp As Integer)
    length = lengthp
    ReDim _magnitude(lengthp, 2) As Integer
End Sub

你也谈到长度,所以你应该记住你是在指定数组的上限,而不是长度。

答案 1 :(得分:1)

Dim成员变量的_magnitude语句出现在构造函数之前。按如下方式更改您的代码:

  Dim _magnitude(,) As Integer '<<Changed. Don't set the bounds here, just declare the variable
  Public Property magnitude As Integer(,)
    Get
      Return _magnitude
    End Get
    Set(ByVal value As Integer(,))
      _magnitude = value
    End Set
  End Property

  Public Sub New(ByVal lengthp As Integer)
    length = lengthp 'Sets 5 to the length property.
    ReDim _magnitude(length, 2) '<<Added. Set the bounds AFTER the length property has been set
  End Sub