2014-05-14 28 views
0

當我使用變量定義整數數組的大小時,出現錯誤:「IndexOutOfRangeException was unhandled」。但是,如果我只是把與我使用的變量相同的值,它就可以工作。當尺寸由變量定義時,爲什麼索引超出範圍?

我會更好下面的評論解釋:

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 

希望你們明白我在問什麼。

回答

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

_magnitude成員變量的Dim聲明發生在構造函數之前。更改您的代碼,如下所示:

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