【发布时间】:2017-04-19 22:49:57
【问题描述】:
我正在使用对象列表创建一个小 C# 应用程序,我有一个非常菜鸟的问题:
首先我填充我的对象 'A' ,然后我添加到名为 'lstA' 的列表中:
List<List<A>> Lst_LstA = new List<List<A>>(); // List of List<A>
List<A> lstA = new List<A>(); // List of my object <A>
A myA = new A();
A.xxx = xx;
A.yyy = yy;
lstA.Add(A);
Lst_LstA.Add(lstA);
lstA.Clear();
我的问题是什么?非常简单:当我调用 lstA.Clear() 时,它会清除我的 lstA 列表,完美,但是......它也清除了我的 lst_LstA 列表。
我需要清除 lstA 列表,但只有这些列表。
为什么 Clear() 也修改了其他列表?如何简单地解决这个问题?
非常感谢,
最好的问候,
【问题讨论】:
-
这是因为
List<>是一个引用类型...如果要添加为新List,请使用.Add(new List<>(a)。或使用.ToList() -
谢谢@TripleEEE 没关系 :)
标签: c# .net list ienumerable