Introduction to 4 deep copy methods in C#

高洛峰
Release: 2017-01-19 13:17:17
Original
1886 people have browsed it

1: Implementation using reflection

public static T DeepCopy<T>(T obj)
{
  //如果是字符串或值类型则直接返回
  if (obj is string || obj.GetType().IsValueType) return obj;
 
  object retval = Activator.CreateInstance(obj.GetType());
  FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);
  foreach (FieldInfo field in fields)
  {
    try { field.SetValue(retval, DeepCopy(field.GetValue(obj))); }
    catch { }
  }
  return (T)retval;
}
Copy after login

2: Implementation using xml serialization and deserialization

public T DeepCopy<T>(T obj)
    {
      object retval;
      using (MemoryStream ms = new MemoryStream())
      {
        XmlSerializer xml = new XmlSerializer(typeof(T));
        xml.Serialize(ms, obj);
        ms.Seek(0, SeekOrigin.Begin);
        retval = xml.Deserialize(ms);
        ms.Close();
      }
      return (T)retval;
    }
Copy after login

3: Using binary sequence Implementation and deserialization

public static T DeepCopy<T>(T obj)
{
  object retval;
  using (MemoryStream ms = new MemoryStream())
  {
    BinaryFormatter bf = new BinaryFormatter();
    //序列化成流
    bf.Serialize(ms, obj);
    ms.Seek(0, SeekOrigin.Begin);
    //反序列化成对象
    retval = bf.Deserialize(ms);
    ms.Close();
  }
  return (T)retval;
}
Copy after login

4: Implemented using silverlight DataContractSerializer for use on the silverlight client

public static T DeepCopy<T>(T obj)
    {
      object retval;
      using (MemoryStream ms = new MemoryStream())
      {
        DataContractSerializer ser = new DataContractSerializer(typeof(T));
        ser.WriteObject(ms, obj);
        ms.Seek(0, SeekOrigin.Begin);
        retval = ser.ReadObject(ms);
        ms.Close();
      }
      return (T)retval;
Copy after login

Supplementary: First A deep copy has been implemented through recursion.

For more related articles introducing the 4 deep copy methods in C#, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template