0
我試圖寫一個函數,其中將有兩個列表:更新數據更改我的所有數據
- 原始列表(fooList)
- 列表包含額外的信息(fooWithExtList)
但不知道爲什麼當我連接另一個列表中的文本時,它也更新我的原始列表中的信息。
下面的代碼:
var fooDataList = new List<Foo>();
fooDataList.Add(new Foo { Bar = "Test1" });
fooDataList.Add(new Foo { Bar = "Test2" });
fooDataList.Add(new Foo { Bar = "Test3" });
fooDataList.Add(new Foo { Bar = "Test4" });
var fooList = new List<Foo>();
var fooWithExtList = new List<Foo>();
//assign foodata to fooList
fooDataList.ForEach(fdl => fooList.Add(fdl));
//assign foodata to fooWithExtList
fooDataList.ForEach(fdl => fooWithExtList.Add(fdl));
//set the fooWithExtList with extra info
fooWithExtList.ForEach(fwel => fwel.Bar = fwel.Bar + "ext");
//merge the list
fooList = fooList.Concat(fooWithExtList).ToList();
結果:
Test1ext Test2ext Test3ext Test4ext Test1ext Test2ext Test3ext Test4ext
期待:
的Test1的Test2 TEST3 TEST4 Test1ext Test2ext Test3ext Test4ext
點網小提琴這裏:https://dotnetfiddle.net/0nMTmX
您正在使用相同的_reference_,因此您會得到三個列表,指向第相同的數據。需要了解引用和值類型之間的區別。 – Steve
類似於[C#Concepts:Value vs Reference Types](http://www.albahari.com/valuevsreftypes.aspx) – Steve