这个例子显示了我的问题。我正在使用VB.net 2010
Public Class Form1
Public Class BonoType
Public name As String
End Class
Private tory As New List(Of BonoType)
Private tory1 As New List(Of BonoType)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim gg As New BonoType
gg.name = "Boopsy"
tory.Add(gg)
gg = New BonoType
gg.name = "Dipsy"
tory.Add(gg)
tory1 = tory
Label1.Text = tory1(0).name
Label2.Text = tory1(1).name
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
tory(1).name = "Goose"
Label1.Text = tory1(0).name
Label2.Text = tory1(1).name
TextBox1.Text = tory(1).name
End Sub
End Class
“Goose”不仅存储在tory(1)中,还存储在tory1(1)中,我该如何阻止它。
答案 0 :(得分:0)
我相信你的问题就在这里
tory1 = tory
你将tory1设为等于保守党。它很难跟随你想要完成的事情,但在我看来它们实际上是绑在一起的。你可能想要考虑
var thisTory = new tory
Label1.Text = thisTory(0).name
Label2.Text = tory1(1).name
答案 1 :(得分:0)
我认为问题在于,使用tory1 = tory,您只需创建一个返回原始对象的引用。您需要创建一个新对象。
即,在VB中:
Dim tory as New List(of String);
Dim tory2 as List(of String)
然后,当你想复制tory2时:
tory2 = New List(of String)(tory)
C#:
List<String> tory = new List<String>();
List<String> tory2;
tory2 = new List<String>(tory);