参见英文答案 >
ToList()— Does it Create a New List?12个
鉴于以下代码:
鉴于以下代码:
public class Item { private int _id; private int _order; private string _name; public int Id { get { return _id; } set { _id = value; } } public int Order { get { return _order; } set { _order = value; } } public string Name { get { return _name; } set { _name = value; } } public static IList<Item> InitList1() { var list = new List<Item> { new Item { Id = 1,Order = 1,Name = "Alpha" },new Item { Id = 2,Order = 2,Name = "Bravo" },new Item { Id = 3,Order = 3,Name = "Charlie" },new Item { Id = 4,Order = 4,Name = "Delta" } }; return list; } } class Program { static void Main(string[] args) { // Initialize the lists IList<Item> list1 = Item.InitList1(); IList<Item> list2 = list1.ToList(); IList<Item> list3 = new List<Item>(list1); // Modify list2 foreach (Item item in list2) item.Order++; // Modify list3 foreach (Item item in list3) item.Order++; // Output the lists Console.WriteLine(string.Format("\nList1\n=====================")); foreach (Item item in list1) Console.WriteLine(string.Format("Item - id: {0} order: {1} name: {2}",item.Id,item.Order,item.Name)); Console.WriteLine(string.Format("\nList2\n=====================")); foreach (Item item in list2) Console.WriteLine(string.Format("Item - id: {0} order: {1} name: {2}",item.Name)); Console.WriteLine(string.Format("\nList3\n=====================")); foreach (Item item in list3) Console.WriteLine(string.Format("Item - id: {0} order: {1} name: {2}",item.Name)); Console.Write("\nAny key to exit..."); Console.ReadKey(); } }
输出将是:
List1 ===================== Item - id: 1 order: 3 name: Alpha Item - id: 2 order: 4 name: Bravo Item - id: 3 order: 5 name: Charlie Item - id: 4 order: 6 name: Delta List2 ===================== Item - id: 1 order: 3 name: Alpha Item - id: 2 order: 4 name: Bravo Item - id: 3 order: 5 name: Charlie Item - id: 4 order: 6 name: Delta List3 ===================== Item - id: 1 order: 3 name: Alpha Item - id: 2 order: 4 name: Bravo Item - id: 3 order: 5 name: Charlie Item - id: 4 order: 6 name: Delta Any key to exit...
有人可以向我解释一下:
>为什么在创建新列表(list2和list3)后,这些列表上的操作会影响list1(以及随后的其他两个列表)?和
>如何创建list1的新实例并在不影响list1的情况下修改它?
解决方法
你实际上得到了一个“浅拷贝”.是的,列表被复制,但它们仍然指向原始项目.
想想这样.列表实际上并不包含它包含的项目,而是包含对它的引用.因此,当您复制列表时,新列表只包含对原始项的引用.你需要的是这样的
IList newlist = new List<Item>(); foreach(item anItem in myList) { newList.Add(item.ReturnCopy()); }
返回副本看起来像这样:
public Item ReturnCopy() { Item newItem = new Item(); newItem._id = _id; newItem._order = _order; newItem._name = _name; return newItem }
这将复制项目中的所有数据,但保留原始数据.有很多模式和接口可以提供更好的实现,但我只是想告诉你它是如何工作的.
@H_403_14@ @H_403_14@