如何修复错误:" RankException未处理"?

时间:2014-05-13 20:30:40

标签: arrays vb.net

每当运行以下代码时,我都会收到此错误。

Public Sub test()
    Dim mg As Array = {{2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}}
    Dim pt As Point = New Point(2, 3)

    If mg(1)(0) = pt.X And mg(1)(1) = pt.Y Then 'Checking to see if mg(1) and pt are equal
        Debug.Print("pt and mg are equal")
    End If
End Sub

3 个答案:

答案 0 :(得分:2)

您是否有理由不将mg声明为Point()?似乎这样可以简化比较:

Dim mg As Point() = New Point(){New Point(2, 2), New Point(2, 3), New Point(2, 4), New Point(2, 5), New Point(2, 6)}

If mg(1) = pt Then...

否则,正如其他人所说,你的数组声明是错误的。您似乎可以使用Array.GetValue访问mg数组中的值。

If mg.GetValue(1, 0) = pt.X AndAlso mg.GetValue(1, 1) = pt.Y Then...

答案 1 :(得分:1)

试试2-dimensional array

Public Sub test()
    Dim mg(,) As Integer = {{2, 2}, {2, 3}, {2, 4}, {2, 5}, {2, 6}}
    Dim pt As System.Drawing.Point = New System.Drawing.Point(2, 3)

    If mg(1, 0) = pt.X And mg(1, 1) = pt.Y Then 'Checking to see if mg(1) and pt are equal
        Debug.Print("pt and mg are equal")
    End If
End Sub

答案 2 :(得分:0)

您所展示的是在您的代码期望的数组()()时声明一个数组(,)。

要按原样使用代码,请禁用声明,声明数组如下:

Dim mg = {({2, 2}), ({2, 3}), ({2, 4}), ({2, 5}), ({2, 6})}

要修改代码以按原样使用声明,请执行以下操作:

If mg(1, 0) = pt.X AndAlso mg(1, 1) = pt.Y Then

(我使用Option Infer On。)

参考:How to: Initialize an Array Variable in Visual Basic