2013-12-19 57 views
1

我在代码中定义的一个结构,这个结构”价值观结构列表不改变

Structure Parcel 
     Public name As String 
     Public type As String     
    End Structure 

    Dim ParcelList As New List(Of Parcel) 

然后我想一些值设置为列表的元素列表这名对我

For Each myParcel As Parcel In ParcelList 
       If (myParcel.name = "Parcel1") Then 
        myParcel.type="Type1" 
       End If 
      Next 

不幸的是重视我的列表中不发生任何变化。我究竟做错了什么?

回答

-3

当字符串检查使用equals代替“=”。

  If (myParcel.name.equals("Parcel1")) Then 
       myParcel.type="Type1" 
      End If 

字符串实际上是“对象”。在比较字符串时(例如StringA = StringB),可以检查内存中字符串的分配而不是字符串的内容。

更妙的是:

  If (myParcel.name.ToUpper().equals(Cstr("Parcel1").toUpper())) Then 
       myParcel.type="Type1" 
      End If 

你忽略任何差异的情况下,明智的方式。 例如: myParcel.name =“测试”

   myParcel.name.equals("test") 
        is False 
      myParcel.name.ToUpper().equals(Cstr("test").toUpper()) 
        is true 
4

由于ParcelStructure,它是由值,通过收集迭代时,您正在修改的结构的副本通过。

为了更好地理解这种情况,您应该了解For Each究竟是什么。您的代码可以翻译成:

Dim enumerator As List(Of Parcel).Enumerator = ParcelList.GetEnumerator() 
While enumerator.MoveNext() 
    ' Here you have a local copy of your Structure 
    Dim myParcel As Parcel = enumerator.Current 
    Dim flag As Boolean = Operators.CompareString(myParcel.name, "Parcel1", False) = 0 
    If flag Then 
     ' Here you modify your local copy 
     myParcel.type = "Type1" 
    End If 
End While 

如果ParcelClass,它会按引用传递,因此我们将不会创建本地副本和线myParcel.type = "Type1"将改变正确的对象现有的收藏。

1

正如已经指出的,这是因为您正在修改值类型的本地副本。这一轮的一种方法是访问列表按顺序的项目,并与新型替代序号值类型:

For i As Integer = 0 To ParcelList.Count - 1 
     If ParcelList(i).name = "Parcel1" Then 
      ParcelList(i) = New Parcel With {.name = ParcelList(i).name, .type = "Type1"} 
     End If 
    Next 

不过说真的,你应该将内在张力结构更改为类