简体   繁体   English

如何更改某些包含引用类型对象的复制列表而不更改原始列表

[英]How can I make changes to some Copied list that contains reference-type objects without changing the original one

I Have List<PropertyDetails> OriginalList which I clone it to another list by : List<PropretyDetails> CopiedList = OriginalList.ToList(); 我有List<PropertyDetails> OriginalList ,它通过以下方式将其克隆到另一个列表: List<PropretyDetails> CopiedList = OriginalList.ToList();

Now I pass the CopiedList to some method that alters it. 现在,我将CopiedList传递给一些更改它的方法。

Myproblem is the alterations are reflected to the OriginalList 我的问题是更改反映到OriginalList

A reference type is really a pointer to an object. 引用类型实际上是指向对象的指针。 And because PropertyDetails is also a reference type, copying the list just gives you a new list of pointers that point to the original objects. 而且由于PropertyDetails也是引用类型,因此复制列表仅会为您提供指向原始对象的指针的新列表。 As Habbib pointed out, you'll have to create copies of the objects in the list, and build a new list that contains these copies. 正如Habbib指出的那样,您必须在列表中创建对象的副本,并构建一个包含这些副本的新列表。

If you are doing something like this: CopiedList[0] = OriginalList[0] and the objects are reference types, CopiedList[0] will be pointing to the same address in memory than OriginalList[0]. 如果您正在执行以下操作:CopiedList [0] = OriginalList [0]并且对象是引用类型,则CopiedList [0]将指向内存中与OriginalList [0]相同的地址。 Thus, when you change something for CopiedList[0] you will be editing the same object in memory in OriginalList. 因此,当您更改CopiedList [0]的内容时,您将在OriginalList中的内存中编辑同一对象。 When you are copying the objects to the CopiedList you will need to create a new instance of that object with the same values of the OriginalList. 当您将对象复制到CopiedList时,将需要使用与OriginalList相同的值创建该对象的新实例。 You can take a look at ICloneable Interface which is the standard way of doing this. 您可以看看ICloneable接口 ,这是执行此操作的标准方法。 Also there are other questions related to this, like for example this one: Deep cloning objects 也有与此相关的其他问题,例如这一问题: 深度克隆对象

I think what you want to do is clone your list to make some changes without having the original one modified, right? 我认为您想要做的就是克隆您的列表以进行一些更改,而无需修改原始列表,对吗?

Check @ajm answers in here: https://stackoverflow.com/a/222640/1435499 在这里检查@ajm答案: https ://stackoverflow.com/a/222640/1435499

You can actually create a extension method to clone the list :), it shouldn't be hard. 实际上,您可以创建一个扩展方法来克隆列表:),这并不难。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM