简体   繁体   中英

Why do I get an error when I am declaring a Matrix/Array as a global variable?

When I press Start in "Visual Studio 2011 Ultimate 12", where I am working, it says:

"InvalidOperationException was unhandled, an exception was caught by the debugger, and user settings indicate that a break should occur. This thread is stopped with only external code frames on the call stack. External code frames are typically from framework code but can also include other optimized modules which are loaded in a target process."`

My code:

    Public Class Form1
    Private matrix As Integer(,) = PopulateMatrix()

    Private Sub ClickMouse(sender As Object, e As DataGridViewCellMouseEventArgs) Handles DataGridView.CellMouseClick
        MsgBox(e.Clicks & e.ColumnIndex & e.RowIndex)

        matrix(e.ColumnIndex, e.RowIndex) = 0

        Matrixtomatrixdef(matrix)
    End Sub

    Private Function PopulateMatrix() As Integer(,)  
        Dim matrix(10, 10) As Integer
        For rown = 0 To 9
            For columnn = 0 To 9
                matrix(columnn, rown) = 1
            Next
        Next
        Return matrix
    End Function

    Private Sub Matrixtomatrixdef(matrix As Integer(,))     
        Dim Matrixdef(10, 10) As Integer
        For rown = 0 To 9
            For columnn = 0 To 9
                Matrixdef(columnn, rown) = matrix(columnn, rown)
                Debug.Write(Matrixdef(columnn, rown).ToString & " ")
            Next
            Debug.WriteLine("")
        Next
    End Sub
End Class

Because your trying to call the function as the class is being initialized, and you cannot do that. Declare the variable, but set it later like in the constructor or at another appropriate point.

Private matrix As Integer(,)

Public Sub New() 'constructor
  matrix = PopulateMatrix
End Sub 

You can't call a method on the same object as part of the field definition. Instance methods are only available after all fields have been initialized.

The correct code:

   Private matrix As Integer(,)
Private Sub populate1s(sender As Object, e As EventArgs) Handles Button3.Click
    matrix = PopulateMatrix()
End Sub

    Private Function PopulateMatrix() As Integer(,)
        Dim matrix(10, 10) As Integer
        For rown = 0 To 9
            For columnn = 0 To 9
                matrix(columnn, rown) = 1
            Next
        Next
        Return matrix
    End Function


Public Sub ClickMouse(sender As Object, e As DataGridViewCellMouseEventArgs) Handles LRInc.CellMouseClick
    matrix(e.ColumnIndex, e.RowIndex) = 0
    For rown = 0 To 9
        For columnn = 0 To 9
            Debug.Write(matrix(columnn, rown).ToString & " ")
        Next
        Debug.WriteLine("")
    Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM