欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#中4种深拷贝方法介绍

程序员文章站 2023-08-17 19:39:18
1:利用反射实现 public static t deepcopy(t obj) { //如果是字符串或值类型则直接返回 if (...

1:利用反射实现

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;
}

2:利用xml序列化和反序列化实现

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;
    }

3:利用二进制序列化和反序列化实现

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;
}

4:利用silverlight datacontractserializer实现,用于在silverlight 客户端使用

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;

补充:第一个已经通过递归实现了深拷贝。