我有课。
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/