当我将Matrix / Array声明为全局变量时,为什么会出现错误?

时间:2013-05-22 18:04:18

标签: arrays vb.net datagridview matrix click

当我在“Visual Studio 2011 Ultimate 12”中按“开始”时,我正在工作,它说:

“InvalidOperationException未处理,调试器捕获到异常,并且用户设置指示应该发生中断。此线程在调用堆栈上仅使用外部代码帧停止。外部代码帧通常来自框架代码但可以还包括在目标进程中加载​​的其他优化模块。“

我的代码:

    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

3 个答案:

答案 0 :(得分:1)

因为您尝试将该函数作为类调用正在初始化,并且您无法执行此操作。声明变量,但稍后在构造函数或其他适当的位置设置它。

Private matrix As Integer(,)

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

答案 1 :(得分:0)

您不能在同一个对象上调用方法作为字段定义的一部分。实例方法仅在初始化所有字段后可用。

答案 2 :(得分:0)

正确的代码:

   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