在 VB.NET 中更改数组值

发布于 2024-10-10 11:01:45 字数 709 浏览 2 评论 0原文

我使用二维数组将数据存储在网格中,所有数据都是一和零。默认情况下,该数组全为零。当我尝试使用 variable(y)(x) = 1 修改数组中的值(其中 x 和 y 是范围内的整数)时,它将整个列中的值更改为 1,而不仅仅是单个单元格。

例如:

Public cells(19)() As Integer

'Code to  populate it with zeros goes here

Public Sub modifyCells(ByVal x As Integer, ByVal y As Integer)
    cells(x)(y) = 1
End Sub

每当我调用 modifyCells(0,0) 时,我都会得到每个子数组的值,如下所示:

1,0,0,0,0,0,0,0,0, 0

而我希望这种情况仅发生在第一个子数组(即 cells(0)(0) = 1 处的值且仅该值)。

我该如何处理这个问题?提前致谢。

(如果有什么区别,用于填充数组的代码如下)

Public Sub clear()
    Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    For y = 0 To 19
        cells(y) = A1
    Next
End Sub

I'm using a 2D array to store data in a grid and all the data is ones and zeros. By default, the array is all zeros. When I attempt to modify values in the array using variable(y)(x) = 1 where x and y are integers in range it changes the value to 1 in the entire column, not just a single cell.

For example:

Public cells(19)() As Integer

'Code to  populate it with zeros goes here

Public Sub modifyCells(ByVal x As Integer, ByVal y As Integer)
    cells(x)(y) = 1
End Sub

Whenever I call modifyCells(0,0) I get the value of every sub-array looking like this:

1,0,0,0,0,0,0,0,0,0

Whereas I want this to happen only to the first sub array (i.e the value at cells(0)(0) = 1 and only that value).

How can I manage this? Thanks in advance.

(If it makes any difference the code used to populate the array is below)

Public Sub clear()
    Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
    For y = 0 To 19
        cells(y) = A1
    Next
End Sub

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

旧人 2024-10-17 11:01:45

您的问题是您正在使用完全相同的数组填充每一行。您需要将局部变量定义移至循环中:

Public Sub clear()
    For y = 0 To 19
        Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        cells(y) = A1
    Next
End Sub

Your problem is that you are populating each row with exactly the same array. You need to move your local variable definition into the loop:

Public Sub clear()
    For y = 0 To 19
        Dim A1() As Integer = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
        cells(y) = A1
    Next
End Sub
我要还你自由 2024-10-17 11:01:45

您基本上是将相同数组的引用添加到单元格中的每个位置。

试试这个:

Public Sub clear()
    For y = 0 To 19         
        cells(y) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}     
    Next 
End Sub 

You are basically adding a reference to the same array to each position in cells.

Try this instead:

Public Sub clear()
    For y = 0 To 19         
        cells(y) = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}     
    Next 
End Sub 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文