C# 将列表复制到另一个列表(新列表不应引用旧列表)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13758044/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:42:33  来源:igfitidea点击:

Copying a list to another (new list should not reference to old list)

c#

提问by Sunny

Possible Duplicate:
How do I clone a generic list in C#?

可能的重复:
如何在 C# 中克隆通用列表?

I want to copy a list to another in C#. The problem is that existing methods like copytocreates a new list from another list. But if I make some changes to new list the old list also gets changed. Its because of their reference type behaviour. If there any way (apart from foreachloop) to create a new list from another list which will not reference the same object

我想在 C# 中将一个列表复制到另一个列表。问题在于现有方法如copyto从另一个列表创建一个新列表。但是如果我对新列表进行一些更改,旧列表也会更改。这是因为它们的引用类型行为。如果有任何方法(除了foreach循环)从另一个不会引用同一对象的列表中创建一个新列表

回答by Roy Dictus

So what you want is a deep copy of the list -- where the 2nd list contains copies of the elements of the 1st list. In that case, when an element of any list changes, the other list remains unchanged.

所以你想要的是列表的深层副本——其中第二个列表包含第一个列表元素的副本。在这种情况下,当任何列表的元素发生变化时,另一个列表保持不变。

How to do that, depends on whether the elements of your list are reference types or value types. A value type list can be easily cloned like so:

如何做到这一点,取决于列表中的元素是引用类型还是值类型。值类型列表可以很容易地克隆,如下所示:

List<int> deepCopy = new List<int>(originalList);

For a reference type list, you can use serialization, like so:

对于引用类型列表,您可以使用序列化,如下所示:

public List<MyObject> DeepCopy()
{
    MemoryStream ms = new MemoryStream();
    BinaryFormatter bf = new BinaryFormatter();
    bf.Serialize(ms, this);

    ms.Position = 0;
    return (List<MyObject>) bf.Deserialize(ms);
}