我遇到的好奇问题。
我遍历一个从字符串拆分创建的数组。在迭代中,我对数组中的项进行了修改。 (在项目中添加字符(字符串,就此而言)
在for循环中,更改受到影响,但在for循环后直接使用此数组时,更改似乎被“删除”,并且使用原始数组(如更改之前)。
这可能是一个byRef,byVal问题......但我并没有特意将其传递到任何地方。
也许有人可以对这种行为有所了解。我已经在for循环中构建了一个列表,并在我更改字符串时添加它。然后我在select语句中使用该列表。这有效,但我很好奇为什么数组会丢弃它的变化。
此致
Dim descriptionSplit() As String
descriptionSplit = Split(unit.itemDescription, "[")
'add the cut "[" back to the strings . "[" was cut from the strings when it was split ON "["
For Each splitSection As String In descriptionSplit.
'add back the '[' char
splitSection = "[" & splitSection
Debug.Print(splitSection)
Next
'look for and find TAGS
For Each splitSection As String In descriptionSplit
Select Case True
'Look for #UNIT# TAG
'######## HERE, the array has reverted to the original copy....
Case splitSection.Contains("[U]")
答案 0 :(得分:4)
如果使用For Each
,splitSection
变量不是对数组项的引用,而是数组项的副本。因此,数组本身永远不会改变。
使用For
和索引变量迭代数组并直接访问数组以进行更改。
我对Visual Basic的约会并不是很新,但在C#中应该有点像这样:
for (int i = 0; i < descriptionSplit.Length; i++)
descriptionSplit[i] = "[" + descriptionSplit[i];
我会无耻地删除James发布的代码并在此处发布,以便完整并隐藏我无法从内存中编写VB.NET: - )
For index As Integer = 0 To descriptionSplit.Length-1
descriptionSplit(index) = "[" & descriptionSplit(index)
Next
答案 1 :(得分:1)
您实际上并没有在这里修改数组,当您对值类型执行For Each
时,您会得到每个项目的副本
splitSection = "[" & splitSection
仅适用于循环的上下文中,这些更改不会反映在数组中。
如果您的目标是在处理项目时修改这些项目,那么您应该使用基本的for
循环来索引数组,例如。
For index As Integer = 0 To descriptionSplit.Length-1
descriptionSplit(index) = "[" & descriptionSplit(index)
Next
答案 2 :(得分:1)
你永远不会改变阵列。你做的是以下几点:
为循环变量分配新值。
这就是全部。这不会改变数组中的值。
答案 3 :(得分:0)
这是因为这段代码:
For Each splitSection As String In descriptionSplit
Select Case True
...
您的splitSection
成为descriptionSplit
的字符串,该拆分数组是原始字符串的数组。
您需要更改原始分组的数组。
我不是VB
的专家,但考虑到你用标签C#
写了:
for(var i=0; i< descriptionSplit.Length; i++) {
descriptionSplit[i] = "[" + descriptionSplit[i];
}
答案 4 :(得分:0)
好的,从目前为止我所看到的:
您只是为变量splitSection
分配一个新引用,它只存在于循环的范围内 - 因此数组中的引用永远不会改变。
解决方案:
Dim descriptionSplit() As String
descriptionSplit = Split(unit.itemDescription, "[")
For i As Integer = 0 To descriptionSplit.Length - 1
descriptionSplit(i) = "[" & descriptionSplit(i)
Next
希望这有帮助!