【发布时间】:2023-03-10 21:38:01
【问题描述】:
我正在尝试编写一个包含两个列表的函数:
- 原始列表(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
dot net fiddle:https://dotnetfiddle.net/0nMTmX
【问题讨论】:
-
您使用的是相同的 reference,因此您会得到三个列表,它们都指向相同的数据。需要了解引用类型和值类型之间的区别。