c# - 为什么更新列表中的实例会更新另一个列表中的相同实例?

标签 c#

我有课。

public class abc
{
    public int i = 0;
    public string a = "";
}

=======================================

现在,我要在类型为 abc 类的列表中插入一些记录

List<abc> c = new System.Collections.Generic.List<abc>();
abc a = new abc();
a.a = "1";
a.i = 1;
c.Add(a);

a = new abc();
a.a = "1";
a.i = 2;
c.Add(a);

===========================================

创建一个列表变量并添加一些过滤记录。

List<abc> temp = new System.Collections.Generic.List<abc>();

temp.AddRange(c.Where(i => i.i == 1));

=============================================

通过执行以下代码行查询 = 也会更改 c 变量。

我知道两者都指向同一个内存位置。有什么办法可以修复这段代码吗?

foreach (abc d in temp)
{
    d.i = 10;
}

最佳答案

不是“为什么更新列表会更新另一个列表?”

是“为什么更新列表中的实例会更新另一个列表中的相同实例?”

因为您正在使用一个和这个类的相同实例。

List<abc> list1 = new List<abc>();
list1.Add(new abc());  // new abc() creates an instance of the abc() class. Let's call this instance myInstance

List<abc> list2 = new List<abc>();
list2.Add(list1[0]);  // Here you add the same instance (ie. myInstance) to the list2

list1[0].a = 5;  // You modify the instance myinstance

Console.WriteLine(list2[0].a);   // Returns "5"  (because it is always the same instance myIsntance)

要避免这种行为,您有 2 种解决方案:

创建一个 Clone 方法来克隆一个具有相同值的 abc 实例。

public class abc
{
    public int i = 0;
    public string a = "";

    public abc Clone(abc instanceToClone)
    {
        abc result = new abc();
        result.i = instanceToClone.i;
        result.a = instanceToClone.a;
    }
}

或者用结构替换类(然后你有一个值类型但你不能有字段初始值设定项)

public struct abc
{
    public int i;  // Initialized by default to 0
    public string a;  // Initialized by default to null
}

我建议你阅读这个优秀的 article了解 C# 的“基本”概念。 (不是那么容易,但真的很重要)

关于c# - 为什么更新列表中的实例会更新另一个列表中的相同实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14583473/

相关文章:

c# - 为什么我必须为 Code First/Entity Framework 使用无参数构造函数

c# - 从 NHibernate 配置文件生成数据库

c# - 如何对控件的属性进行分类以显示在 Blend 和 Visual studio 设计器中的适当部分?

javascript - 与 DropDownList 和 TexBox 元素的宽度相同

c# - 调用 Task.Delay() 并在几分钟后询问还剩多少时间

c# - WPF应用程序关闭的原因是什么

C# 从流中读取视频/音频/图像文件元数据

c# - 读取 CSV 到对象列表

c# - 是否有任何事件告诉应用程序何时发生了垃圾收集?

c# 图表控件删除条形图中条形之间的空格