在 VB.NET 中更改数组值
我使用二维数组将数据存储在网格中,所有数据都是一和零。默认情况下,该数组全为零。当我尝试使用 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的问题是您正在使用完全相同的数组填充每一行。您需要将局部变量定义移至循环中:
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:
您基本上是将相同数组的引用添加到
单元格
中的每个位置。试试这个:
You are basically adding a reference to the same array to each position in
cells
.Try this instead: