One, the T in the List<t> object is the case of the value type (int type, etc.)
A list of value types can be copied directly using the following methods:
list<t> oldlist = new list<t> (); Oldlist.add (..); list<t> NewList = new list<t> (oldlist);
Second, the T in the List<t> object is the case of a reference type (for example, a custom entity class)
1. The list of reference types cannot be copied with the above methods, only the references to the objects in the list are copied, and can be copied with the following extension methods:
Static class Extensions {public static ilist<t> clone<t> (this ilist<t> listtoclone) where T:iclon Eable { return Listtoclone.select (item = (T) item. Clone ()). ToList (); } Of course the preceding question is that the object in the list implements the ICloneable interface}
2. Another way to make a deep copy of a reference object in a serialized manner, this method is the most reliable
public static T clone<t> (t realobject) { using (Stream objectstream = new MemoryStream ()) { //using System . Runtime.serialization serialization and deserialization complete the replication of the referenced object iformatter formatter = new BinaryFormatter (); Formatter. Serialize (Objectstream, realobject); Objectstream.seek (0, seekorigin.begin); Return (T) formatter. Deserialize (Objectstream); }}
3. Using System.Xml.Serialization to realize serialization and deserialization
public static T clone<t> (t realobject) { using (Stream stream=new MemoryStream ()) { XmlSerializer Serializer = new XmlSerializer (typeof (T)); Serializer. Serialize (stream, realobject); Stream. Seek (0, seekorigin.begin); Return (T) serializer. Deserialize (stream);} }
Third, the above several objects deep copy test
The test is as follows:
Using system;using system.collections.generic;using system.collections; using system.linq;using System.Text;using System.io;using system.runtime.serialization;using System.Runtime.Serialization.Formatters.Binary; namespace linq{[Serializable] public class TT {private string name = ""; public string Name {get {return Name;} set {name = value;} } private String sex = ""; public string Sex {get {return Sex;} set {sex = value;} }} class Linqtest {public static T clone<t> (t realobject) {using (Stream Objectstream = new Memory Stream ()) {IFormatter formatter = new BinaryFormatter (); Formatter. Serialize (Objectstream, realobject); Objectstream.seek (0, Seekorigin.begin); Return (T) formatter. Deserialize (Objectstream); }} public static void Main () {list<tt> lsttt = new list<tt> (); TT TT1 = new TT (); Tt1. Name = "A1"; Tt1. Sex = "20"; Lsttt. ADD (TT1); list<tt> l333 = new list<tt> (); l333. ADD (clone<tt> (lsttt[0)); L333[0]. Name = "333333333"; } }}
In this article on the list object in C # deep copy of the problem is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we support topic.alibabacloud.com.