Home >Backend Development >C++ >How to Efficiently Clone Generic Lists in C#?
The efficient cloning of the generic list of generics: in -depth analysis
Question statement:
In C#, how to highly cloned a list of generic objects? Although the single object in the list is cloned, the list itself lacks a built -in "clone" method.
Method 1: The type of cloning
The clone is very simple for the generic list of value types. Just create a new list of the same content as the original list:
Method 2: Deeply copy the reference type
<code class="language-csharp">List<你的类型> newList = new List<你的类型>(oldList);</code>If the generic list contains the reference type and needs to be copied in depth (instead of shallow replication), you can use the following
interface method:
This method ensures that all objects in the clone list are completely independent with the objects in the original list.
ICloneable
Method 3: Use a copy constructor to cloning
<code class="language-csharp">List<ICloneable> oldList = new List<ICloneable>(); List<ICloneable> newList = new List<ICloneable>(oldList.Count); oldList.ForEach((item) => { newList.Add((ICloneable)item.Clone()); });</code>
When the list elements are not realized
but have a duplicate constructor, you can use different cloning strategies:This method uses a copy of the new instance in the clone list with a copy constructor.
Other suggestions ICloneable
<code class="language-csharp">List<你的类型> oldList = new List<你的类型>(); List<你的类型> newList = new List<你的类型>(oldList.Count); oldList.ForEach((item) => { newList.Add(new 你的类型(item)); });</code>Although the interface can provide convenience, it depends on ensuring the in -depth copy of all members, which may bring problems. You can consider the following alternative scheme:
Copy the constructor: For the type with a clear definition state, the replication constructor provides a method that is more effective and easy to maintain to create depth copy. Factory method: A method similar to
can be used to return new instances of types that need to be needed.
ICloneable
The above is the detailed content of How to Efficiently Clone Generic Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!