【问题标题】:Update data in another list change all my data更新另一个列表中的数据会更改我的所有数据
【发布时间】:2023-03-10 21:38:01
【问题描述】:

我正在尝试编写一个包含两个列表的函数:

  1. 原始列表(fooList)
  2. 包含额外信息的列表 (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,因此您会得到三个列表,它们都指向相同的数据。需要了解引用类型和值类型之间的区别。

标签: c# linq list


【解决方案1】:

如果您希望它们作为单独的实体存在,您需要创建添加到第一个列表中的 Foo 类的不同实例。否则,您在三个列表中添加对同一实例的引用,因此对 Foo 实例之一所做的更改会反映在三个列表中。

一个可能的解决方案。假设你的 Foo 类有一个 Copy 方法......

public class Foo
{
    public string Bar {get;set;}
    public Foo(string bar)
    {
        Bar = bar;
    }
    public Foo Copy()
    {
        Foo aCopy = new Foo(this.Bar);
        return aCopy;
    }
}

现在你可以写了

//assign copies of foodata to fooList
fooDataList.ForEach(fdl => fooList.Add(fdl.Copy()));

正如上面评论中指出的,好的阅读是
C# Concepts: Value vs Reference Types
MSDN documentation
Or on this same site from Jon Skeet

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-16
    • 2017-01-14
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多