In C#, the list of cloned generic objects is a challenge, because the built -in
class does not directly "clone ()". However, there are several ways to achieve this function.
List<T>
The value type clone
If the element of the list is a value type, you can simply create a new list containing the same elements:
Use icloneable cloned reference type
<code class="language-csharp">List<MyValueType> newList = new List<MyValueType>(oldList);</code>
If the element is a reference type, and you need to be deeply copied (that is, the new list and its elements have nothing to do with the original list), you can use the interface:
"ICloneable" in the above code is replaced with the actual element type of ICloneable
.
<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>
ICloneable
but has a copy constructor, you can use the following methods:
This method uses a copy constructor to create a new instance of each element.
ICloneable
Custom clone method
<code class="language-csharp">List<MyReferenceType> oldList = new List<MyReferenceType>(); List<MyReferenceType> newList = new List<MyReferenceType>(oldList.Count); oldList.ForEach(item => newList.Add(new MyReferenceType(item)));</code>
For convenience, you can encapsulate any of these methods in the custom cloning method:
This method accepts a generic list and returns a new clone list, selecting the appropriate cloning method according to the type of element.
The above is the detailed content of How to Effectively Clone Generic Lists in C#?. For more information, please follow other related articles on the PHP Chinese website!