当前位置: 移动技术网 > IT编程>开发语言>c# > 简单谈谈C#中深拷贝、浅拷贝

简单谈谈C#中深拷贝、浅拷贝

2019年07月18日  | 移动技术网IT编程  | 我要评论
object.memberwiseclone 方法 创建当前 object 的浅表副本。 protected object memberwiseclone(

object.memberwiseclone 方法

创建当前 object 的浅表副本。

protected object memberwiseclone()

memberwiseclone 方法创建一个浅表副本,方法是创建一个新对象,然后将当前对象的非静态字段复制到该新对象。 如果字段是值类型的,则对该字段执行逐位复制。 如果字段是引用类型,则复制引用但不复制引用的对象;因此,原始对象及其复本引用同一对象。

例如,考虑对象x引用对象 a 和 b , 对象 b 依次引用对象 c。 x 的浅表副本创建一个新对象 x2,该对象也引用对象 a 和 b。 相比而言,x 的深层副本创建一个新对象 x2,该对象引用新对象 a2 和 b2(分别为 a 和 b 的副本)。 b2 又引用新对象 c2,c2 是 c 的副本。 该示例阐释了浅层和深层复制操作之间的区别。

有很多方法可以实现深层复制操作,前提是浅表复制操作由 memberwiseclone 方法执行但不符合您的需求。

这些要求包括:

调用要复制的对象的类构造函数以创建含有从第一个对象中提出的属性值的第二个对象。 这假定对象的值完全由类构造函数定义。

调用 memberwiseclone 方法创建的对象的浅表副本,然后将指定新的对象,其值均相同,原始对象的任何属性或字段的值是引用类型。 该示例中的 deepcopy 方法阐释了这种方法。

序列化要深层复制的对象,然后将序列化的数据还原到另一个对象变量。

使用带递归的反射执行的深层复制操作。

 下面的示例演示 memberwiseclone 方法。 它定义了 shallowcopy 方法,该方法通过调用 memberwiseclone 方法来在 person 对象上执行浅表复制操作。 它还定义了在 person 对象上执行深层复制操作的deepcopy 方法。

using system;
 
public class idinfo
{
  public int idnumber;
 
  public idinfo(int idnumber)
  {
    this.idnumber = idnumber;
  }
}
 
public class person
{
  public int age;
  public string name;
  public idinfo idinfo;
 
  public person shallowcopy()
  {
    return (person)this.memberwiseclone();
  }
 
  public person deepcopy()
  {
    person other = (person) this.memberwiseclone();
    other.idinfo = new idinfo(this.idinfo.idnumber);
    return other;
  }
}
 
public class example
{
  public static void main()
  {
    // create an instance of person and assign values to its fields.
    person p1 = new person();
    p1.age = 42;
    p1.name = "sam";
    p1.idinfo = new idinfo(6565);
 
    // perform a shallow copy of p1 and assign it to p2.
    person p2 = (person) p1.shallowcopy();
 
    // display values of p1, p2
    console.writeline("original values of p1 and p2:");
    console.writeline("  p1 instance values: ");
    displayvalues(p1);
    console.writeline("  p2 instance values:");
    displayvalues(p2);
 
    // change the value of p1 properties and display the values of p1 and p2.
    p1.age = 32;
    p1.name = "frank";
    p1.idinfo.idnumber = 7878;
    console.writeline("\nvalues of p1 and p2 after changes to p1:");
    console.writeline("  p1 instance values: ");
    displayvalues(p1);
    console.writeline("  p2 instance values:");
    displayvalues(p2);
 
    // make a deep copy of p1 and assign it to p3.
    person p3 = p1.deepcopy();
    // change the members of the p1 class to new values to show the deep copy.
    p1.name = "george";
    p1.age = 39;
    p1.idinfo.idnumber = 8641;
    console.writeline("\nvalues of p1 and p3 after changes to p1:");
    console.writeline("  p1 instance values: ");
    displayvalues(p1);
    console.writeline("  p3 instance values:");
    displayvalues(p3);
  }
 
  public static void displayvalues(person p)
  {
    console.writeline("   name: {0:s}, age: {1:d}", p.name, p.age);
    console.writeline("   value: {0:d}", p.idinfo.idnumber);
  }
}
// the example displays the following output:
//    original values of p1 and p2:
//     p1 instance values:
//       name: sam, age: 42
//       value: 6565
//     p2 instance values:
//       name: sam, age: 42
//       value: 6565
//   
//    values of p1 and p2 after changes to p1:
//     p1 instance values:
//       name: frank, age: 32
//       value: 7878
//     p2 instance values:
//       name: sam, age: 42
//       value: 7878
//   
//    values of p1 and p3 after changes to p1:
//     p1 instance values:
//       name: george, age: 39
//       value: 8641
//     p3 instance values:
//       name: frank, age: 32
//       value: 7878

为了实现深度复制,我们就必须遍历有相互引用的对象构成的图,并需要处理其中的循环引用结构。这无疑是十分复杂的。幸好借助.net的序列化和反序列化机制,可以十分简单的深度clone一个对象。

原理很简单,首先将对象序列化到内存流中,此时对象和对象引用的所用对象的状态都被保存到内存中。.net的序列化机制会自动处理循环引用的情况。然后将内存流中的状态信息反序列化到一个新的对象中。

这样一个对象的深度复制就完成了。在原型设计模式中clone技术非常关键。

using system;
using system.io;
using system.runtime.serialization.formatters.binary;
 
namespace clonedemo
{
  [serializable]
  class democlass
  {
    public int i = 0;
    public int[] iarr = { 1, 2, 3 };
 
    public democlass clone1() //浅clone
    {
      return this.memberwiseclone() as democlass;
    }
 
    public democlass clone2() //深clone
    {
      memorystream stream = new memorystream();
      binaryformatter formatter = new binaryformatter();
      formatter.serialize(stream, this);
      stream.position = 0;
      return formatter.deserialize(stream) as democlass;
    }
  }
 
  class program
  {
    static void main(string[] args)
    {
      democlass a = new democlass();
      a.i = 10;
      a.iarr = new int[] { 8, 9, 10 };
      democlass b = a.clone1();
      democlass c = a.clone2();
 
      // 更改 a 对象的iarr[0], 导致 b 对象的iarr[0] 也发生了变化 而 c不会变化
       a.iarr[0] = 88;
 
      console.writeline("memberwiseclone");
      console.writeline(b.i);
      foreach (var item in b.iarr)
      {
        console.writeline(item);
      }
 
      console.writeline("clone2");
      console.writeline(c.i);
      foreach (var item in c.iarr)
      {
        console.writeline(item);
      }
 
      console.readline();
    }
  }
}

以上所述就是本文的全部内容了,希望大家能够喜欢。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网