很好的一段代码,解释了深复制、浅复制和 不复制

[ 766 查看 / 0 回复 ]

  1. class DrawBase:System.Object , ICloneable
  2.     {
  3.         public string name = "jmj";
  4.         public DrawBase()
  5.         {
  6.         }
  7.        
  8.         public object Clone()
  9.         {
  10.             return this as object;      //引用同一个对象
  11.             return this.MemberwiseClone(); //浅复制
  12.             return new DrawBase() as object;//深复制
  13.         }
  14.     }
  15. class Program
  16. {

  17.         static void Main(string[] args)
  18.         {
  19.             DrawBase rect = new DrawBase();
  20.             Console.WriteLine(rect.name);
  21.             DrawBase line = rect.Clone() as DrawBase;
  22.             line.name = "a9fs3";
  23.             Console.WriteLine(rect.name);
  24.             DrawBase ploy = line.Clone() as DrawBase;
  25.             ploy.name = "lj";
  26.             Console.WriteLine(rect.name);

  27.             Console.WriteLine(object.ReferenceEquals(line, ploy));
  28.             Console.ReadLine();
  29.         }
  30. }
复制代码
TOP